[英]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: 我有一个动作
edit_multiple
,它接受一个ID列表,例如:
def edit_multiple
@products = Product.find(params[:product_ids])
end
and a routes.rb: 和一个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
的路径的视图中的products
变量中的products
集合,例如:
<%= 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 请注意,我正在使用Rails 4
如果产品ID以数组形式出现,请使用where
,但find
:
@products = Product.where("id in (?)", params[:product_ids])
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.. 您将获得一个产品ID数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.