0

I have a action edit_multiple which takes a list of id's a such:

def edit_multiple
  @products = Product.find(params[:product_ids])
end

and a routes.rb:

resources: products do
  collection do
    post :edit_multiple
  end
end

and a collection of products in a products variable in a view which I want to pass as the arguments to a path in a link_to something like:

<%= link_to edit_multiple_products_path(:product_ids => products), :method => :post do %>
  update products
<% end %>

when I click the link i get the error:

Couldn't find Product with id=#<ActiveRecord::Relation::ActiveRecord_Relation_Product:0x495c900>

Please note I'm using Rails 4

user2732663
  • 833
  • 2
  • 10
  • 18

2 Answers2

2

If product ids are coming as an array use where, not find:

@products = Product.where("id in (?)", params[:product_ids])
Carlos Drew
  • 1,633
  • 9
  • 17
Sabyasachi Ghosh
  • 2,765
  • 22
  • 33
  • 1
    `find` expects to receive, as an argument, a single id and then return a single product. Using `where` will allow you to send multiple ids and receive back multiple products. – Carlos Drew Sep 16 '13 at 17:34
1

You could also change your view from:

<%= link_to edit_multiple_products_path(:product_ids => products), :method => :post do %>
  update products
<% end %>

to:

<%= link_to edit_multiple_products_path(:product_ids => products.map(&:id)), :method => :post do %>
  update products
<% end %>

and you will get an products ids array..

Matthias
  • 4,355
  • 2
  • 25
  • 34