0

Lets say I have a model topic, and it has one moderator. I want to build a new post for a topic.

In my controller:

@topic = Topic.find(:id)
@moderator = @topic.moderator.build # error points to this line

Error:

undefined method `build' for nil:NilClass
zishe
  • 10,665
  • 12
  • 64
  • 103
Don P
  • 60,113
  • 114
  • 300
  • 432

1 Answers1

1

If the relation is declared in the model as long as it is a has_many you might have been declared:

has_many :posts

So you need to call:

@post = @topic.posts.build

Suppossing you have a has_one relation:

has_one :moderator

@moderator = @post.build_moderator

Solved here:

Using build with a has_one association in rails

See also the Rails guide re: associations. http://guides.rubyonrails.org/association_basics.html

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35