Thursday, December 1, 2011

Use build with has_one and belongs_to association

Suppose we have association between two models as has_one and belongs_to. We want to create the child record with parent record using build method than need to follow below easy steps.

eg. Class User < ActiveRecord::Base
        has_one :profile
      end
      
     Class Profile < ActiveRecord::Base
        belongs_to :user
     end
   
When we are creating the user than required to create associated profile by using below methods:

@user.build_profile or
@user.profile.build

It create associated profile record along with user.

No comments:

Post a Comment