This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#http://blog.plataformatec.com.br/page/3/ | |
#Active Record associations also love blocks | |
#We talked about using blocks when building an Active Record object using new or create, but associations like belongs_to or #has_many also work with that, when calling build or create on them: | |
class User < ActiveRecord::Base | |
has_many :posts | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :user | |
end | |
# has_many | |
user = User.first | |
user.posts.build do |post| | |
post.title = "Active Record <3 Blocks" | |
post.body = "I can give tap a break! <3 <3 <3" | |
end | |
# belongs_to | |
post = Post.first | |
post.build_user do |user| | |
user.name = "John Doe <3 blocks" | |
user.username = "john.doe" | |
user.password = "john123" | |
end |
No comments:
Post a Comment