0
这个问题很简单。 请看看我的架构:模型的before_action和嵌套属性
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
和
class Item < ApplicationRecord
belongs_to :parent
end
的问题:当创建一个家长,为什么它提出以下错误?
undefined method `build' for nil:NilClass
我应该如何设置它,以便可以在创建父项的同时添加项目记录?
那就是它!非常感谢您的帮助!在“Items”表中,新记录添加了一个合适的“user_id”值。另一个问题是:在“家长”表中,我的新记录具有item_id = nill值。我只是想知道我是否还需要在“父母”表中使用这个item_id列。你怎么看?有没有简单的方法可以解决这个问题? – Kaczor
为什么你需要父母表中的item_id 你可以通过使用项目对象 像@ Item.parent –