【问题标题】:Update and create multiple records in a single form in Rails 3在 Rails 3 中以单一形式更新和创建多条记录
【发布时间】: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


    【解决方案1】:

    我最终通过已经具有正确关联的父模型来保存多条记录。

    我关注了Railscast #196 Nested Model Forms,这与上面非常相似,只是保存到另一个模型并将accepts_nested_attributes_for放在该模型的 *.rb 中。

    记得移动路线。

    将控制器代码移动到父模型的接收动作中。

    我在查看器中的表单现在看起来像这样(haml 格式):

    = form_for @user, :remote => true do |f|
      = f.fields_for :ingredient_costs do |builder|
        // fields inserted here
    

    我花了几个小时才意识到我必须使用builder.object... 才能找到我真正感兴趣的孩子。 .object 类对我来说并不明显。

    无论如何,希望这对某人有用。我认为 SybariteManoj 的答案看起来很划算,但我无法让它发挥作用。

    【讨论】:

      【解决方案2】:

      你可以试试sn-p:

      @costs = []
      params[:ingredient_costs].each do |ingredient_cost|
        if ingredient_cost[:id].blank?
          cost = IngredientCost.create(ingredient_cost)
          @costs << cost
        else
          cost = IngredientCost.find(ingredient_cost[:id])
          cost.update_attributes(ingredient_cost)
          @costs << cost
        end
      end
      

      附:我还没有测试过。但是对于重新渲染有错误的编辑页面,@costs 变量会包含有错误的数据。

      【讨论】:

      • 这看起来是一个不错的解决方案,但我无法让它工作。我通过了鳍,控制台中没有错误,但东西没有保存。我在.blank? 之后放入了一个调试器,它成功地达到了这一点,我认为.create() 没有正确创建,我可以在它的位置使用另一个函数吗?
      • 尝试cost = IngredientCost.new(ingredient_cost),然后使用cost.save保存。可能这会起作用。
      • 不幸的是,它也不起作用。我刚刚重新排列它以通过嵌套属性。在父模型中使用accepts_nested_attributes_for。这似乎工作正常。感谢您的意见。
      • 没问题。 :) 我今晚会检查一下,并会为未来的访客更新正确的解决方案。并添加您的答案并将其标记为已接受。 :)
      • 完全测试后会做。
      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2011-09-23
      • 1970-01-01
      相关资源
      最近更新 更多