Kaczor
Kaczor

Reputation: 1

before_action and nested attributes for models

The question is really simple. Please, take a look at my schema:

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

This is how models looks like:

class Parent < ApplicationRecord
  has_one :item

  accepts_nested_attributes_for :item
  before_create :set_something 

  def set_something
    self.item.build
  end
end

and

class Item < ApplicationRecord
  belongs_to :parent
end

The question: When creating a Parent, why does it raise the following error?

undefined method `build' for nil:NilClass

How should I set this up so that I can add and item record at the same time as creating a parent?

Upvotes: 0

Views: 141

Answers (1)

Ankur Pohekar
Ankur Pohekar

Reputation: 139

Try using

def set_something
    build_item
end

The model Parent has_one :item. In Rails, the has_one association adds a helper method build_association(attributes = {}) to the owner class, and not association.build(attributes = {}). This is the reason that you are getting the error undefined method 'build' for nil:NilClass.

Please see the has_one documentation for more details on has_one association.

Upvotes: 1

Related Questions