Building a calendar navigation in Rails (controller and view links) - ruby-on-rails-3

Trying to get the next month when clicking the link_to. I've done the following in the view.
index.html.erb
<table class="rota">
<thead>
<tr>
<!-- Element will carry the month number for initializing this table correctly. -->
<th class="month"-<%= #date_range.month %>">Days</th>
<% #hospitals.each do |hsp| %>
<th class="hospital-<%= hsp.shortname %>"><%= hsp.name %></th>
<% end %>
</tr>
</thead>
<tbody>
<% #date_range.each do |d| %>
<tr>
<th><%= d.to_s(:short) %></th>
<% #hospitals.each do |hsp| %>
<td class="day-<%= d.to_s(:short) %> hospital-<%= hsp.shortname %>"> </td> <!--Class on each td to make it identifiable -->
<% end %>
</tr>
<% end %>
</tbody>
</table>
<%= form_tag rota_days_path, :method => 'get' do %>
<p>
<%= link_to 'Previous Month', rota_days_path(:beginning_of_month => #beginning_previous) %>
<%= link_to 'Next Month', rota_days_path(:beginning_of_month => #beginning_next) %>
</p>
<% end %>
Controller.rb
class RotaDaysController < ApplicationController
# GET /rota_days
# GET /rota_days.json
# load_and_authorize_resource
respond_to :json, :html
def index
#rota_days = RotaDay.all
#hospitals = Hospital.all
#t1 = Date.today.at_beginning_of_month
#t2 = Date.today.end_of_month
#dates = (#t1..#t2) #Concat variable t1 + t2 together
# #next_month = Date.today + 1.month(params[: ??? ] #Old
if params[:next_month]
# #next_month = Date.today >> 1
#next_month = params[:next_month] + 1.month
#t1 = #next_month.at_beginning_of_month
#t2 = #next_month.end_of_month
#dates = (#t1..#t2)
end
#title = "Rota"
respond_to do |format|
format.html # index.html.erb
format.json { render json: #rota_days }
end
end
I have identified that the reason why this may not be working is in because of the following in my controller #next_month = params[:next_month] + 1.month the last two called methods is defined only on time/date objects. but not on fixnum/string objects. I understand I am missing something from this
Update
I have found that the actual issue is that the `params[:next_month] is a string and I am trying to add a date to to it. Which means I need to convert the string to a date/time object.
Console output:
Started GET "/rota_days" for 127.0.0.1 at 2012-12-14 22:14:36 +0000
Processing by RotaDaysController#index as HTML
User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
RotaDay Load (0.0ms) SELECT `rota_days`.* FROM `rota_days`
Hospital Load (1.0ms) SELECT `hospitals`.* FROM `hospitals`
Rendered rota_days/index.html.erb within layouts/application (23.0ms)
Role Load (0.0ms) SELECT `roles`.* FROM `roles` INNER JOIN `roles_users` ON `roles`.`id` = `roles_users`.`role_id` WHERE `roles_users`.`user_id` = 1 AND `roles`.`name` = 'Administrator' LIMIT 1
Completed 200 OK in 42ms (Views: 39.0ms | ActiveRecord: 1.0ms)

I've taken your code and refined it a bit to handle navigating between the months
class RotaDaysController < ApplicationController
respond_to :json, :html
def index
#title = "Rota"
#rota_days = RotaDay.all
#hospitals = Hospital.all
# Find the beginning of the month we are currently displaying
# it can be either passed in through the params[:beginning_of_month]
# which is a string we parse into a date by calling '2013-01-01'.to_date
# By wrapping the .to_date call in .try(:to_date), the call will not throw
# a NoMethodError if no params[:beginning_of_month] is passed in and thus
# we would call nil.to_date => throws NoMethodError
#
# If no parameter is passed in we want to display the current month
#beginning_current = params[:beginning_of_month].try(:to_date) || Date.current.beginning_of_month
# Let's build the date range of the month to display
# The nice thing about date / time ranges is that you can iterate over them
# in the view to create the calendar interface we are looking for
#date_range = (#beginning_current.beginning_of_month..#beginning_current.end_of_month)
# Build references for previous and next month for navigation
# We can use the beginning of the previous and next month as a reference
# for which month to display.
#beginning_next = (#beginning_current + 1.month).beginning_of_month.to_s
#beginning_previous = (#beginning_current - 1.month).beginning_of_month.to_s
respond_to do |format|
format.html # index.html.erb
format.json { render json: #rota_days }
end
end
end
In the view you can use these strings in the link_to helpers.
<%= form_tag rota_days_path, :method => 'get' do %>
<p>
<%= link_to 'Previous Month', rota_days_path(:beginning_of_month => #beginning_previous) %>
<%= link_to 'Next Month', rota_days_path(:beginning_of_month => #beginning_next) %>
</p>
<% end %>
You can also iterate over date ranges to display each date in the view
<% #date_range.each do |day| %>
...
<% end %>
I hope this helps. Feel free to ask any questions you like, but it might take me 'till tomorrow to get back to you.

Related

Rails delete action is not being run, and renders 200 OK

I am having trouble implementing the DELETE action on any object that I have for my application.
To show you the general code for my delete action in the Group Controller:
def destroy
#group = Group.find(params[:id])
respond_to do |format|
if #group.delete
format.html { redirect_to group_path }
format.json { head :no_content }
else
format.html { redirect_to group_path }
format.json { head :no_content }
end
end
end
And the code for my View layout:
<h1>My Groups</h1>
<table>
<tr>
<th>Name</th>
<th>Users</th>
<th></th>
<th></th>
</tr>
<% #groups.each do |group| %>
<tr>
<td><%= group.name %></td>
<td>
<% group.memberships.each do |membership| %>
<%= User.find(membership.user_id).name %>
<br/>
<% end %>
</td>
<td><%= link_to 'Show', group %></td>
<td><%= link_to 'Destroy', group, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Group', new_group_path %>
I am unable to delete the group object even though the rails server log gives me back a 200 OK response. The returned page is a blank screen:
Started DELETE "/groups/2" for 127.0.0.1 at 2013-03-19 01:22:01 +0800
Processing by GroupsController#destroy as HTML
Parameters: {"authenticity_token"=>"aH+z0DlL7NeoVlxda8Td76WdnrH7/G8UyWDqbJcTu9w=", "id"=>"2"}
Completed 200 OK in 0ms (ActiveRecord: 0.0ms)
ActiveRecord wasn't used and there were no changes to the database. There were no such problems in the past, but I only realized that I could not delete any kind of object recently.
I have been trying to find solutions to similar problems found on the net, but unfortunately it seems like no one has had this problem yet.
Update 1:
The following is my application layout:
<!DOCTYPE html>
<html>
<head>
<%= csrf_meta_tag %>
<title>Home</title>
<%= javascript_include_tag :application %>
<%= stylesheet_link_tag :application, :media => "all" %>
<%= javascript_include_tag "/javascripts/main.js" %>
<%= stylesheet_link_tag "/css/main.css" %>
</head>
<body>
<%= yield %>
</body>
</html>
But when I use the console to delete the object. It works:
1.9.3-p194 :003 > Group.find(23).delete
Group Load (0.5ms) SELECT "groups".* FROM "groups" WHERE "groups"."id" = $1 LIMIT 1 [["id", 23]]
SQL (3.0ms) DELETE FROM "groups" WHERE "groups"."id" = 23
=> #<Group id: 23, name: "groupie", created_at: "2013-03-18 15:29:42", updated_at: "2013-03-18 15:29:42", user_id: nil>
I just found the solution to the question. I actually wrote a code for an around_filter that messed up the destroy session for every controller:
around_filter :clear_registration_id_on_destroy_session, only: :destroy
def clear_registration_id_on_destroy_session
is_filter_active = (controller_path == 'devise/sessions' && params[:action] == 'destroy')
if is_filter_active && user_signed_in?
if current_user.update_attribute(:device_platform, nil)
logger.info "Updated device platform attributes to nil"
end
if current_user.update_attribute(:registration_id, nil)
logger.info "Updated registration id attributes to nil"
end
yield
end
end
The problem is that I didn't yield anything for any other controller other than devise:sessions#destroy.
So for those who are as forgetful as me, please remember to think about the other conditions when is_filter_active is not true.
def clear_registration_id_on_destroy_session
is_filter_active = (controller_path == 'devise/sessions' && params[:action] == 'destroy')
if is_filter_active && user_signed_in?
if current_user.update_attribute(:device_platform, nil)
logger.info "Updated device platform attributes to nil"
end
if current_user.update_attribute(:registration_id, nil)
logger.info "Updated registration id attributes to nil"
end
yield
else
yield
end
end
It sounds like your delete link is just acting as a link to the show action, as the method option is not being picked up.
You need to have the appropriate javascript included in your application layout, as the delete link requires JS to use the correct HTTP method.
If you are using Rails >= 3.1 make sure you have the following in the header of the layout file you are using for rendering the page:
<%= javascript_include_tag :application %>
Also make sure you have the csrf_meta_tag in your layout:
<%= csrf_meta_tag %>

wicked wizard passing arguments to steps

I would like to make a smooth streamlined process for placing customer orders.
I feel the best tool for the job is a wizard - unless there are other suggestions?
I need to pass arguments to next steps in my wizard.
My controller looks like this:
include Wicked::Wizard
steps :item, :customization, :upsell
def show
# #order_session_id = params[:order_session_id]
#order = Order.new
#order.order_session_id = params[:order_session_id]
case step
when :item
#items = Item.all # change with group...
when :customization
# item = Item.find(#order.item_id)
# item = Item.find(params[:item_id])
item = Item.find(1)
#customizations = item.customizations.split("|")
when :upsell
#upsells = Upsell.find_all_by_group_id(item.group_id)
end
render_wizard
end
def update
#order_session_id = params[:order_session_id]
#order.attributes = params[:order]
render_wizard #order
end
The view for item looks like this:
<%= form_for #order, url: wizard_path(:customization), :method => :get do |f| %>
<table border="1">
<% #items.each do |item| %>
<tr>
<td class="item_selection" onclick="$(this).children('input').attr('checked', 'checked');return false;">
<%= f.label :item_id, "#{item.name}" %>
<%= f.radio_button(:item_id, item.id) %>
</td>
</tr>
<% end %>
</table>
<div class="actions">
<%= f.submit "Continute" %>
</div>
<% end %>
I need to pass the selected item_id to the customization step so that the next part of the wizard can work.
How can I do this?
Thanks
You can pass parameters in the url after the step parameter.
wizard_path(:step_1, item: item)

Updating quantity in Rails Form

I'm building a simple inventory app that keeps track of the quantity of an item.
In a basic form I would be updating item_quantity with whatever arbitrary number I type in.
But how would I create a form/code that would allow me to tag on +20 on top of the already existing item quantity?
You could do it with jquery/javascript
Something like:
In your view:
<%= f.text_field :item_quantity, :id => 'item_quanity' %>
+20
In javascript:
$(function() {
$('#increment_item_quantity').on('click', function(e) {
e.preventDefault();
var currentVal = parseInt($('#item_quantity').val());
$('#item_quantity').val(currentVal + 20);
});
});
You'd probably want to make sure the currentVal is a number (since parseInt('') => NaN)
And then submit as usual
Or
If you wanted to do this via a form:
In your view:
<%= form_for #item, incr_quantity_path(#item) do |f| %>
<%= f.submit %>
<% end %>
Then in your controller:
def incr_quantity
#item = Item.find(params[:id])
# I'd probably move the increment logic into the model
#item.quantity += 20
#item.save
# respond to it however you want
end
Or if you want to increment the value by what's entered:
Model:
class Item < AR::Base
...
attr_accessible :incr_quantity_by
def increment_quantity_by
quantity += incr_quantity_by
end
...
end
View:
<%= form_for #item, incr_quantity_path(#item) do |f| %>
<%= f.text_field :incr_quantity_by
<%= f.submit %>
<% end %>
Controller:
def incr_quantity
#item = Item.find(params[:id])
#item.increment_quantity_by
#item.save
# respond to how you want
end

Update don´t get the value of local when doing an update using i18n

I have tried to use i18n internationalization in my application.
It works very well when I do a Show (index), Create, and Edit. My problem is when I do an update.
When I press the update button I don´t get the :locale value back
Normaly I get these values back.
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
level: '5_3'
menu_item: '5'
menu_level: '5_3_1'
action: index
controller: communication_mails
locale: dk
The URL looks like:
localhost:3000/dk/communication_mails
When I press the Edit button I get these values back. (The “Button” is a link). Locale is still ok.
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
level: '5_3'
menu_item: '5'
menu_level: '5_3_2'
action: edit
controller: communication_mails
locale: dk
id: '2'
The URL now looks like:
localhost:3000/dk/communication_mails/2/edit
My problem is when I now press the “Update” button under the form field the redirection don´t get the value of locale back... It instead uses the ID.
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
level: '5_3'
menu_item: '5'
menu_level: '5_3_1'
action: index
controller: communication_mails
locale: '2'
The URL now looks like:
localhost:3000/2/communication_mails
My route looks something likes this:
scope "/:locale" do
resources :communication_mails
end
resources :communication_mails do
collection do
get 'communication_mails'
post 'communication_mails'
put 'communication_mails'
end
end
root :to => redirect("/dk/tests/")
match '/communication_mails/:id/edit(.:format)', :to => 'communication_mails#edit'
match '/communication_mails/:id/', :to => 'communication_mails#index'
match '/communication_mails', :to => 'communication_mails#index'
My Controller is made like this.
def edit
#communication_mail = CommunicationMail.find(params[:id])
#show_calendars = Calendar.where(:calendar_priority => '1')
#show_email_text = CommunicationMail.find_by_sql("SELECT calendars.id,
calendar_name, communication_mail_headline, communication_mail_text
FROM calendars LEFT OUTER JOIN communication_mails
ON communication_mails.communication_mail_calendar_id = calendars.id
WHERE communication_mails.communication_mail_priority = '1'")
end
def update
#communication_mail = CommunicationMail.update(params[:id], params[:communication_mail])
#show_calendars = Calendar.where(:calendar_priority => '1')
#show_email_text = CommunicationMail.find_by_sql("SELECT calendars.id,
calendar_name, communication_mail_headline, communication_mail_text
FROM calendars LEFT OUTER JOIN communication_mails
ON communication_mails.communication_mail_calendar_id = calendars.id
WHERE communication_mails.communication_mail_priority = '1'")
if #communication_mail
redirect_to communication_mails_path(:menu_item => '5', :level => '5_3', :menu_level => '5_3_1'),
:notice => 'Opdateringen af E-mail tekst lykkedes'
else
redirect_to communication_mails_path(:menu_item => '5', :level => '5_3', :menu_level => '5_3_1'),
:notice => 'Opdateringen af E-mail tekst lykkedes IKKE'
end
end
I have solved many questions by looking through these pages. But I can´t find an answer to this one.
I hope some one can help me out. Thanks in in advance.
UPDATE
My routes looks like this:
GET /:locale/communication_mails/communication_mails(.:format) communication_mails#communication_mails
POST /:locale/communication_mails/communication_mails(.:format) communication_mails#communication_mails
PUT /:locale/communication_mails/communication_mails(.:format) communication_mails#communication_mails
GET /:locale/communication_mails(.:format) communication_mails#index
POST /:locale/communication_mails(.:format) communication_mails#create
GET /:locale/communication_mails/new(.:format) communication_mails#new
GET /:locale/communication_mails/:id/edit(.:format) communication_mails#edit
GET /:locale/communication_mails/:id(.:format) communication_mails#show
PUT /:locale/communication_mails/:id(.:format) communication_mails#update
DELETE /:locale/communication_mails/:id(.:format) communication_mails#destroy
The form I use to send and update the data
<%= form_for(#communication_mail) do |f| %>
<table class="toggle_header2">
<tr>
<td class="nobr width50px font_size13 font_weight_bold color03 border_left">
<%= t('forms.calendar') %>
</td>
<td class="color03 border_right">
<%= collection_select(:communication_mail,
:communication_mail_calendar_id,
#show_calendars,
:id,
:calendar_name,
{:include_blank => true },
{:prompt => true})
%>
</td>
</tr>
<tr>
<td class="nobr width50px font_size13 font_weight_bold color03 border_left">
<%= t('forms.headline') %>
</td>
<td class="color03 border_right">
<%= f.text_field :communication_mail_headline, :class => 'width350px' %>
</td>
</tr>
<tr>
<td class="nobr align_top font_size13 font_weight_bold color03 border_left">
<%= t('forms.text') %>
</td>
<td class="color03 border_right">
<%= f.text_area :communication_mail_text, :class => 'width350px' %>
</td>
</tr>
<tr>
<td class="color03 border_left">
<%= f.hidden_field :communication_mail_priority, :value => '1' %>
</td>
<td class="color03 border_right">
<% if action_name == 'edit' || action_name == 'update' %>
<%= f.submit t('buttons.update') %>
<% else %>
<%= f.submit t('buttons.insert') %>
<% end %>
</td>
</tr>
</table>
<% end %>
If you pick your :locale value from params, you have incorrect approach in your routing.
Update: be sure you are passing :locale value to your routing helpers on update action.
This code will generate routes with scope only for index, show, new, create, edit, update, destroy actions.
scope "/:locale" do
resources :communication_mails
end
This code will add additional routes to :communication_mails, but without scope.
resources :communication_mails do
collection do
get 'communication_mails'
post 'communication_mails'
put 'communication_mails'
end
end
Solution is to combine. You have to define :scope for all of your :communication_mails actions.
scope "/:locale" do
resources :communication_mails do
collection do
get 'communication_mails'
post 'communication_mails'
put 'communication_mails'
end
end
end
Please read documentation about routing (it is basics): http://guides.rubyonrails.org/routing.html

Rails file uploading and Heroku

I have a problem with file uploading on Heroku server.
(Also a hint about the right way of doing such type of things with rails would be greatly appreciated - I'm very new in RoR).
All this code is about uploading some CSV file, then allowing user to tweak couple of settings, and parse file after all. This usually work on localhost (several times I get troubles with value stored in session), but on Heroku it is always die on upload.
In one of the neighborhood questions was written that Heroku store file only during singe instance run, but I still couldn't find anything about this in Heroku's docs. Should I store file data in the db right after upload, so in such case it always be available? The downside - files could be pretty big, about 10-20Mb, it isn't looks nice.
Heroku logs say:
2012-05-21T19:27:20+00:00 app[web.1]: Started POST "/products/upload" for 46.119
.175.140 at 2012-05-21 19:27:20 +0000
2012-05-21T19:27:20+00:00 app[web.1]: Processing by ProductsController#upload
as HTML
2012-05-21T19:27:20+00:00 app[web.1]: Parameters: {"utf8"=>"тЬУ", "authenticit
y_token"=>"aqJFg3aqENfxS2lKCE4o4txxkZTJgPx36SZ7r3nyZBw=", "upload"=>{"my_file"=>
#<ActionDispatch::Http::UploadedFile:0x000000053af020 #original_filename="marina
-AutoPalmaPriceList_2011-07-30.txt", #content_type="text/plain", #headers="Conte
nt-Disposition: form-data; name=\"upload[my_file]\"; filename=\"marina-AutoPalma
PriceList_2011-07-30.txt\"\r\nContent-Type: text/plain\r\n", #tempfile=#<File:/t
mp/RackMultipart20120521-1-10g8xmx>>}, "commit"=>"Upload"}
2012-05-21T19:27:20+00:00 app[web.1]:
2012-05-21T19:27:20+00:00 app[web.1]: LoadError (no such file to load -- CSV):
2012-05-21T19:27:20+00:00 app[web.1]: app/controllers/products_controller.rb:8
2:in `upload'
2012-05-21T19:27:20+00:00 app[web.1]:
2012-05-21T19:27:20+00:00 app[web.1]:
2012-05-21T19:27:20+00:00 app[web.1]: cache: [POST /products/upload] invalidate,
pass
The code itself:
ProductsController:
def import
respond_to do |format|
format.html
end
end
def import_adjust
case params[:commit]
when "Adjust"
#col_default = params[:col_data]
#abort #col_default.to_yaml
#update csv reader with form data, restore filters from params
when "Complete"
#all ok, read the whole file
#abort params.to_yaml
redirect_to import_complete
else
#col_default = nil
end
#read first part of the file
#tmp = session[:import_file]
#csv = []
source = CSV.open #tmp, {col_sep: ";"}
5.times do
line = source.readline
if line.size>0
#line_size = line.size
#csv.push line
end
end
#generate a selection array
#selection = select_tag 'col_data[]', options_for_select([['name','name'], ['brand','brand'], ['delivery_time','delivery_time'], ['price','price']])
##csv = [selection * line_size] + #csv
end
def import_complete
#remove all items
#todo check products with line items will not be destroyed.
Product.destroy_all
#abort params.to_yaml
map = {}
cnt = 0
#todo check for params count.
params[:col_data].each do |val|
map[cnt] = val if val != 'ignore'
cnt += 1
end
source = CSV.open session[:import_file], {col_sep: ';'}
source.each do |row|
cnt += 1
if row.size > 0
item = Product.new
map.each do |col, attr|
item[attr] = row[col]
end
item[:provider_id] = params[:adjust][:provider]
item.save
#abort item.to_yaml
end
end
#abort map.to_yaml
#todo response needed.
end
def upload
require 'CSV' #looks like I dont need this in fact.
#tmp = params[:upload][:my_file].path #tempfile
#csv = []
#source = CSV.open #tmp, {col_sep: ";"}
session[:import_file] = params[:upload][:my_file].path
respond_to do |format|
format.html { redirect_to action: 'import_adjust' }
end
end
upload.html.erb:
<h1>Uploaded</h1>
<%= #tmp %>
<% #csv.each do |val| %>
<%= val %>
<% end %>
_form_import.html.erb:
<%= form_for :upload, :html => {:multipart => true}, :url => {action: "upload"} do |f| %>
<%= f.file_field :my_file %>
<%= f.submit "Upload" %>
<% end %>
import_adjust.html.erb:
<h1>New product</h1>
<%= form_for :adjust, :url => {action: "import_adjust"} do |f| %>
<% if #csv %>
<table>
<tr>
<% #line_size.times do |cnt| %>
<td>
<%= select_tag 'col_data[]',
options_for_select([
['--ignore--', 'ignore'],
['name','name'],
['brand','brand'],
['delivery_time','delivery_time'],
['price','price']
], #col_default!=nil ? #col_default[cnt] : nil) %>
</td>
<% end %>
</tr>
<% #csv.each do |val| %>
<tr>
<% val.each do |cell| %>
<td>
<%= cell %>
</td>
<% end %>
</tr>
<% end %>
</table>
<% end %>
<%= f.label :delimiter, 'Разделитель' %>
<%= f.text_field :delimiter %>
<br>
<%= f.label :provider, 'Поставщик' %>
<%#todo default empty option needed! Human mistakes warning! %>
<%= f.select :provider, Provider.all.collect { |item| [item.name, item.id] } %>
<br>
<%= f.label :delimiter, 'Разделитель' %>
<%= f.text_field :delimiter %>
<br>
<%# Adjust for proceed adjusting or Complete for parsing %>
<%= f.submit "Adjust" %>
<%= f.submit "Complete" %>
<% end %>
<%= link_to 'Back', products_path %>
Could you paste the entire controller code? The problem is on line #82, but I can't be 100% confident what line that is if you've stripped the class def and before_filters out.
That said, it looks like the problem is with one of the CSV.open lines. The way you're trying to set session[:import_file] is not guaranteed to work. If you ever run the app on more than one dyno you could have the first request served by your web.1 dyno and the second served by web.2, and they have different file systems and would not be able to see the same temp files.
I'd suggest one of the following:
Do all the processing immediately on the upload and avoid the re-direct.
An improvement on that would be to have the upload store the data somewhere shared and accessible (the database or S3) and have start a background job/process to do the processing.
Best of all would be to upload directly to S3 (I believe the S3 Uploader library can do this, there are probably others) and issue a callback to create a background job to process.
That last option means your web dynos are never tied up handling massive uploads and you don't burden the user with waiting for the latency involved in upload to server->store in S3->schedule background job, it is reduced simply to store in S3 from their perspective.
I have an identical scenario as Lifecoder where a user uploads a file, names the columns using a map_fields plugin (by Andrew Timberlake), and then the file is parsed and processed. Here's how I handle it:
file_field = params[options[:file_field]]
map_fields_file_name = "map_fields_#{Time.now.to_i}_#{$$}"
bucket = S3.buckets[CSV_COUPON_BUCKET_NAME] # gets an existing bucket
obj = bucket.objects[map_fields_file_name]
obj.write( file_field.read )
# Save the name and bucket to retrieve on second pass
session[:map_fields][:bucket_name] = map_fields_file_name
Then on the second pass to process the file, I open the file and read it back into temp for the dyno to process:
# Get CSV data out of bucket and stick it back into temp, so we pick up where
# we left off as far as map_fields is concerned.
bucket = S3.buckets[CSV_COUPON_BUCKET_NAME]
obj = bucket.objects[session[:map_fields][:bucket_name]]
temp_path = File.join(Dir::tmpdir, "map_fields_#{Time.now.to_i}_#{$$}")
File.open(temp_path, 'wb') do |f|
f.write obj.read
end
I had to use the plugin so I could modify the code, as obviously the gem is handled by Heroku and doesn't allow for modifications.