相关疑难解决方法(0)

使用accepts_nested_attributes_for将现有has_many记录添加到新记录

将现有项模型添加到新的付款模型时,会出现错误"无法找到ID = 123的项目,ID = 123".这是一个has_many关系并使用accepts_nested_attributes_for.

class Payment < ActiveRecord::Base
  has_many :items
  accepts_nested_attributes_for :items
  ...

class Item < ActiveRecord::Base
  belongs_to :payment
  ...
Run Code Online (Sandbox Code Playgroud)

付款和项目模型是假设的,但问题是真实的.在保存付款(在创建操作中完成)之前,我需要将项目与付款关联(就像我在新操作中一样).用户在创建付款时需要修改项目的属性(添加帐单代码就是一个例子).

具体来说,错误发生在控制器的创建操作中:

# payments_controller.rb

def new
  @payment = Payment.new
  @payment.items = Item.available # where(payment_id: nil)
end

def create
  @payment = Payment.new payment_params # <-- error happens here
  ...
end

def payment_params
  params.require(:payment).permit( ..., [items_attributes: [:id, :billcode]])
end
Run Code Online (Sandbox Code Playgroud)

lib/active_record/nested_attributes.rb:543:in 'raise_nested_attributes_record_not_found!'紧接在callstack之前.很奇怪ActiveRecord包含payment_id作为搜索条件的一部分.

为了完整,表单看起来像这样......

form_for @payment do |f|
   # payment fields ...
   fields_for :items do |i|
     # item fields    
Run Code Online (Sandbox Code Playgroud)

并在新操作上正确呈现项目.通过表单的params看起来像这样:

{ "utf8"=>"?", …
Run Code Online (Sandbox Code Playgroud)

activerecord ruby-on-rails ruby-on-rails-4

7
推荐指数
2
解决办法
4024
查看次数