Search code examples
ruby-on-railsruby-on-rails-4link-to

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


Solution

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