ruby-on-railshas-many

build_association with has_many Rails


I want to build associated records for non-persisten record in rails.

Let's say I have these models:

class Post
   has_many :comments
end

I want to do something like this:

p = Post.new(text: 'Some post')
p.build_comment(content: 'some comment')

It says

undefined method `build_comment' for #<Post

It works ok for has_one association though

Thanks in advance


Solution

  • In has_many association, you have to do it like this

        p = Post.new(text: 'Some post')
        p.comments.build(content: 'some comment')