Ruby 模型的before\u操作和嵌套属性

Ruby 模型的before\u操作和嵌套属性,ruby,Ruby,问题很简单。 请查看我的模式: ActiveRecord::Schema.define(version: 20170812094528) do create_table "items", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "parent_id"

问题很简单。 请查看我的模式:

ActiveRecord::Schema.define(version: 20170812094528) do

  create_table "items", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "parent_id"
  end

  create_table "parents", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "item_id"
  end

end
这就是模型的外观:

class Parent < ApplicationRecord
  has_one :item

  accepts_nested_attributes_for :item
  before_create :set_something 

  def set_something
    self.item.build
  end
end
我应该如何设置它,以便在创建父项的同时添加和记录项目?

尝试使用

def set_something
    build_item
end
模型父项
有一个:item
。在Rails中,
has_one
关联向所有者类添加一个助手方法
build_关联(attributes={})
,而不是
association.build(attributes={})
。这就是您得到nil:NilClass的未定义方法“build”的错误
的原因


有关has\u one关联的更多详细信息,请参阅。

就是这样!非常感谢你的帮助!在“Items”表中,新记录添加了一个适当的“user\u id”值。另一个问题是:在“Parents”表中,我的新记录具有item_id=nill值。我只是想知道我是否需要“家长”表中的这个item_id列。你怎么认为?有什么简单的方法可以解决这个问题吗?为什么在parents表中需要item_id?您可以使用类似@item.parent的item对象来获取parents对象
undefined method `build' for nil:NilClass
def set_something
    build_item
end