0

This may not be the correct way of doing things, but I'm honestly not sure how else to do it.

I'm creating an import system which will take a serialized string as an input, deserialize it into ActiveRecord objects, and then show the user a confirmation screen that displays all items that will be imported and when the user presses a "save" button, the items are all saved.

I have the deserialization done and I have the confirmation page built so that it shows each item that will be imported.

The last step is a button that when pressed, will save every item.

I thought this was as simple as having something like this in my view:

<%= button_to 'Save Items', :action=> :save_items %>

and this in my controller:

def save_items
  @items_to_save.each do |item|
      item.save
  end
end

(@items_to_save is an array of ActiveRecord objects)

However, because the button_to appears to be actually causing a new request, @items_to_save is lost as soon as the button is pressed.

Is there some better way to tie a button on the view to a controller action so that a new request isn't triggered and my items aren't lost?

TrolliOlli
  • 909
  • 2
  • 10
  • 18

1 Answers1

0

You need to add the some information to your link (params).

You are right that the @items_to_save are lost. The controller global variabel @ is only accessible for the view - not the other way around after using another action.

So you could first select all the id's in your items, put them in an array, add them to the buttons params, when you render it, and then iterate through them when the button is clicked.

# deserialize it into ActiveRecord objects - action
# don't know how your looks - i hope it's understandable 
...
@items_ids = @active_record_objects.ids
...

And then in your view you will add them to your button_to so you can use those ids in the controller action save_items.

<%= button_to "Save Items", action: :save_items, params: {ids: @items_ids} %> 

Now you can iterate through them and save!

def save_items
  Item.where(id: params[:ids]).each(&:save)
end