パパエンジニアのアウトプット帳

30歳に突入した1児のパパエンジニアのブログ

has_oneのbuildはhas_manyと違う

Railsでhas_many :commentsみないな時にbuildするときは@blog.comments.buildだけど、has_oneの場合は.buildはnilエラーになる。

has_oneの場合はbuild_xxxというメソッドがあるので、そちらを使うと言うことを今頃になって知った。

class Blog
  has_one :star
end

@blog = Blog.new
# @blog.star.build →nilエラーになる
@blog.build_star