[英]Mapping through a hash of key/values
I have a form being submitted that is saving multiple records, and the parameters look something like this: 我有一个正在提交的表单正在保存多个记录,并且参数看起来像这样:
{
"utf8"=>"✓",
"_method"=>"put",
"products"=> {
"321" => {
"sale_price"=>"10"
},
"104" => {
"sale_price"=>"10"
}
}
}
Then in my controller, I have this: 然后在我的控制器中,我有这个:
@updated_products = Product.update(params[:products].keys, params[:products].values)
This expects the keys (321, 104) to be IDs. 这期望键(321、104)是ID。
However, I'm using the to_param
in my model to change my urls from IDs to another column value. 但是,我在模型中使用to_param
将URL从ID更改为另一个列值。
Is there a way to take the params[:products].keys
and swap them for the appropriate IDs so I can use IDs in the .update()
statement. 有没有办法采用params[:products].keys
并将它们交换为适当的ID,以便我可以在.update()
语句中使用ID。 I can use Product.find_by_column_name(321).id
to get the id although I don't know how to do this. 我可以使用Product.find_by_column_name(321).id
来获取ID,尽管我不知道该怎么做。 Still new to rails. 仍然是新手。
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。
Looking at the source code here #update
iterates through each key and runs update_attributes
so it goes through all the validations. 在这里 #update
源代码#update
遍历每个键并运行update_attributes
以便它通过所有验证。 You can change your method to 您可以将方法更改为
@updated_products = params[:products].inject([]) do |array, (column_id, attributes)|
product = Product.find_by_column_id column_id
if product.update_attributes(attributes)
array << product
else
array
end
end
This may seem a little complex but it is equal to this one below which is easier to understand and code read 这看似有点复杂,但与下面的内容相同,它更易于理解和阅读代码
@updated_products = []
params[:products].each do |column_id, attributes|
product = Product.find_by_column_id column_id
if product.update_attributes(attributes)
@updated_products << product
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.