Using build with a has_one association in rails

Using build with a has_one association in rails

Asked on January 10, 2019 in Ruby on Rails.
Add Comment


  • 1 Answer(s)

    Using build method signature is different for has_one and has_many associations. 

    class User < ActiveRecord::Base
    has_one :profile
    has_many :messages
    end
    

    Syntax for has_many association:

    user.messages.build
    

    Syntax for has_one association:

    user.build_profile # this will work
     
    user.profile.build # this will throw error
    

    For more details check this link: has_one association

    Answered on January 10, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.