Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: Do I need both belongs_to and has_one

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.

like image 514
Richard77 Avatar asked Nov 18 '12 02:11

Richard77


People also ask

How would you choose between Belongs_to and Has_one?

The difference between belongs_to and has_one is a semantic one. The model that declares belongs_to includes a column containing the foreign key of the other. The model that declares has_one has its foreign key referenced.

What is Belongs_to in Ruby on Rails?

A belongs_to association sets up a connection with another model, such that each instance of the declaring model "belongs to" one instance of the other model.

What has one and belongs to Example?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user .

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


2 Answers

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.

like image 80
cdesrosiers Avatar answered Sep 18 '22 13:09

cdesrosiers


Having just a belongs_to relationship between userprofiles and user does default to has_one. However, it would be wise (Rails-proper) to specify the association on both models.

After all, if you wanted a has_many association (etc) you would want to specify that.

Check out http://guides.rubyonrails.org/association_basics.html for more info

like image 30
abhir Avatar answered Sep 17 '22 13:09

abhir