Rails :: 在嵌套模型形式中,更新 belongs_to "parent" 属性

Rails :: in nested model form, update belongs_to "parent" attributes

我正在构建一个 Rails 应用程序,但我遇到了无法修复的表单问题。 我有一个 order 模型 belongs_to customer 所以当我构建表单时我会 @order = @customer.orders.build

这对保存订单属性很有效,但我也想更新客户属性,但从来没有用过。

如何在同一过程中保存订单和更新 "parent" 客户属性?

感谢您的帮助!

编辑:

客户型号:

class Customer < ActiveRecord::Base
  has_many :orders
end

订购型号:

class Order < ActiveRecord::Base
  belongs_to :customer
  accepts_nested_attributes_for :customer
end

我的项目:

在您的更新操作中,您可以执行如下操作:

def update
  @customer = Customer.find(params[:id])
  if @customer.update_attributes(customer_params.merge({ order_attributes: order_params}))
     render @customer
  end 
end

其中 customer_paramsorder_params 是使用强参数将表单发送的参数列入白名单的方法。

显然,我还没有测试代码,但我应该给你一些指导。

希望对您有所帮助!

您应该在创建方法中更新您的客户。怎么样:

    def create
        @order = current_customer.orders.build order_params
        if @order.save
          @order.customer.update_attributes(order_params[:customer_attributes])
          ...
        else
          ...
        end
      end