【发布时间】:2013-01-31 09:37:08
【问题描述】:
我关注了railscast #198 Edit Multiple Individually,它可以 100% 地从一个表单中编辑多条记录。
但是,如果记录的话,我还想从同一表单创建新记录。即在控制器中评估表单中参数的哈希值,更新那些存在的记录并创建不存在的记录。
此外,如果发生任何验证错误,应将其捕获并传回。
如果新记录的字段不存在,控制器中的此功能将正确更新 @costs = IngredientCost.update(params[:ingredient_costs].keys, params[:ingredient_costs].values).reject { |item| item.errors.empty? }
对于新记录的字段,我目前正在创建一个大的唯一编号作为记录 id(我不确定这样做是否正确),然后返回消息说它无法保存,因为 id不存在,这是意料之中的,因为它不存在。
我在黑暗中尝试了以下两个 sn-ps,但不确定我应该走哪条路..
@costs = IngredientCost.find_or_initialize_by_id(:id => params[:ingredient_costs].keys).update(params[:ingredient_costs].keys, params[:ingredient_costs].values).reject { |i| i.errors.empty? }
和
params[:ingredient_costs].each do |ingredient_cost|
@cost = IngredientCost.find_or_initialize_by_ingredient_id_and_user_id(:ingredient_id => ingredient_cost[1]["ingredient_id"], :user_id => current_user.id)
@cost = IngredientCost.update(:ingredient_id => params[:ingredient_costs][ingredient_cost[0]]["ingredient_id"], :quantity => params[:ingredient_costs][ingredient_cost[0]]["quantity"], :price_per_unit => params[:ingredient_costs][ingredient_cost[0]]["price_per_unit"], :weight_id => params[:ingredient_costs][ingredient_cost[0]]["weight_id"])
似乎都不起作用。
我以前见过这项工作,但用于从一个表单更新/创建嵌套属性。我真的不想走这条路。
【问题讨论】:
标签: ruby-on-rails