I have 2 models, namely user and userprofile. There is a one-to-one relationship between user and userprofile.
class Userprofile < ActiveRecord::Base
attr_accessible :fname, :lname, :iswoman, :age, :urlphoto, :user_id
belongs_to: user
end
class User < ActiveRecord::Base
attr_accessible :name, :provider, :uid
has_one: userprofile
end
I’d like to know whether I need both class to set the connection or having just either belongs_to or has_one is enough? The same is true for the other methods, such as has-many.
You define the association wherever you will need it. If at some point you need to say
user.userprofile, then includehas_one :userprofileinUser. Likewise, if you need to sayuserprofile.user, then includebelongs_to userinUserprofile.In other words, associations are relative. You can specify that model A
has_one :bwithout specifying that model Bbelongs_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_idto the “userprofiles” table.