Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: belongs_to vs has_one

A bit of a newbie question on rails associations.

I have a Bug model, and a Status model. Status is basically just a key/value pair table. Out of the choices available, I would say Bug has_one Status makes the most sense. However, according to this

Content belongs_to ContentTemplate. Go back and look at how I described the problem, and you'll see that it works. With belongs_to, the table accepts responsibility for the foreign key. So Content has a content_template_id. And ContentTemplate doesn't need anything. I can point to it at will. Done.

Bug belongs_to Status would be more appropriate (since Bug should take the foreign key). Semantically, his example makes sense, but mine makes none. Is this just a quirk of rails where in this situation it looks odd, or am I not understanding something/doing it wrong?

like image 230
Matt Briggs Avatar asked May 22 '09 21:05

Matt Briggs


People also ask

What is difference between Has_one and Belongs_to?

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 is Belongs_to in Ruby on Rails?

belongs_to means that the foreign key is in the table for this class. So belongs_to can ONLY go in the class that holds the foreign key. has_one means that there is a foreign key in another table that references this class.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What has and belongs to many or has many through?

Stories can belong to many categories. Categories can have many stories. has_many :through gives you a third model which can be used to store various other pieces of information which don't belong to either of the original models. Person can subscribe to many magazines.


1 Answers

Yes, I think you've just found a slightly odd-looking scenario in Rails. I suppose it might be useful to view "status" as a sort of category to which the bug belongs — in that light, it makes sense.

like image 172
Chuck Avatar answered Oct 02 '22 14:10

Chuck