2017-08-12 134 views
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 

我应该如何设置它,以便可以在创建父项的同时添加项目记录?

回答

1

使用

def set_something 
    build_item 
end 

模型父has_one :item尝试。在Rails中,has_one关联将帮助器方法build_association(attributes = {})添加到所有者类,而不是association.build(attributes = {})。这是你得到错误undefined method 'build' for nil:NilClass的原因。

有关has_one关联的更多详细信息,请参阅has_one documentation

+0

那就是它!非常感谢您的帮助!在“Items”表中,新记录添加了一个合适的“user_id”值。另一个问题是:在“家长”表中,我的新记录具有item_id = nill值。我只是想知道我是否还需要在“父母”表中使用这个item_id列。你怎么看?有没有简单的方法可以解决这个问题? – Kaczor

+0

为什么你需要父母表中的item_id 你可以通过使用项目对象 像@ Item.parent –