ruby-on-rails - 使用 accepts_nested_attributes_for 将现有的 has_many 记录添加到新记录

标签 ruby-on-rails activerecord ruby-on-rails-4

将现有的项目模型添加到新的付款模型时,会出现错误“无法找到 ID=123 的付款项目 ID=”。这是在 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
  ...

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

具体来说,错误发生在 Controller 的创建 Action 中:
# 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
lib/active_record/nested_attributes.rb:543:in 'raise_nested_attributes_record_not_found!'在调用堆栈中紧接在它之前。奇怪的是,ActiveRecord 将payment_id 作为搜索条件的一部分。

为了完整起见,表格看起来像这样......
form_for @payment do |f|
   # payment fields ...
   fields_for :items do |i|
     # item fields    

并且它在新操作上正确呈现项目。通过表单传递的参数如下所示:
{ "utf8"=>"✓",
  "authenticity_token"=>"...",
  "payment"=>{
    "items_attributes"=>{
      "0"=>{"billcode"=>"123", "id"=>"192"}
    },
  }
}

如果有更好的方法来解决这个问题而不使用 accepts_nested_attributes_for我愿意接受建议。

最佳答案

我只需添加一个 item_ids 就可以使用它参数集合(除了 items_attributes )。您应该能够在 Controller 中按摩您的参数,使其看起来像这样

{ "utf8"=>"✓",
  "authenticity_token"=>"...",
  "payment"=>{
    "item_ids"=>[192]
    "items_attributes"=>{
      "0"=>{"billcode"=>"123", "id"=>"192"}
    },
  }
}

更新 1:出于某种原因,这只适用于 item_ids之前 items_attributes在哈希中。还没有评论Rails docs还没有弄清楚原因。

关于ruby-on-rails - 使用 accepts_nested_attributes_for 将现有的 has_many 记录添加到新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090024/

相关文章:

ruby-on-rails - 销毁一些记录需要非常非常长的时间

mysql - Rails has_many/belongs_to 自定义数据库 ActiveRecord::AssociationTypeMismatch 得到 Fixnum

javascript - 在something.js.haml中编写JS if条件

ruby-on-rails - Rails 4 JSON::ParserError (757: 'null' 处的意外标记):

ruby-on-rails - 将一组动态插值参数传递给 rails-i18n?

javascript - Js 无法读取 Rails 表单上输入的属性

ruby-on-rails - Ruby on Rails 4 - 使用什么身份验证 gem?

ruby-on-rails - 做 has_many :through associations work for models that only exist in memory?

ruby-on-rails - 如何在命名空间和根路径的路由中同时拥有一个资源 - Rails 4

mysql - 使用此 sql 搜索在 Rails 中构建复制关联