user2732663
user2732663

Reputation: 833

Ruby-on-Rails convert variable to link_to array param

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

Upvotes: 0

Views: 1428

Answers (2)

Sabyasachi Ghosh
Sabyasachi Ghosh

Reputation: 2785

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

@products = Product.where("id in (?)", params[:product_ids])

Upvotes: 2

Matthias
Matthias

Reputation: 4375

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..

Upvotes: 1

Related Questions