ActiveRecord: Do I need both belongs_to and has_one

后端 未结 2 1312
灰色年华
灰色年华 2021-02-20 00:04

I have 2 models, namely user and userprofile. There is a one-to-one relationship between user and userprofile.



        
2条回答
  •  一生所求
    2021-02-20 00:39

    You define the association wherever you will need it. If at some point you need to say user.userprofile, then include has_one :userprofile in User. Likewise, if you need to say userprofile.user, then include belongs_to user in Userprofile.

    In other words, associations are relative. You can specify that model A has_one :b without specifying that model B belongs_to :a. You simply define what you need. The same goes for one-to-many and many-to-many associations.

    Just be sure to have migrated user_id to the "userprofiles" table.

提交回复
热议问题