Skip to content

Instantly share code, notes, and snippets.

@sonianand11
Created May 16, 2018 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonianand11/6e1b9be64e0e502e3216325d972d2281 to your computer and use it in GitHub Desktop.
Save sonianand11/6e1b9be64e0e502e3216325d972d2281 to your computer and use it in GitHub Desktop.
how to use build method to create new object
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
post = Post.first
comment = Comment.new
comment.post_id = post.id
puts comment.post_id # prints 1
comment = post.comments.build
puts comment.post_id # prints 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment