itsme213 asked:

has_one vs. belongs_to: what is the difference?

Tags:

Question says it all.

(3 attempts)

dickdawg answered:

These relationships describe the composition and aggregate associations possible between classes. In OO terms, a class is composed of another if you have the following:

class Foo
  def initialize
    @bar = Bar.new
  end
end
if you kill an instance of Foo, the Bar instance evaporates as well - this is composition. On the other hand, if you had:
class Foo
  def initialize(bar)
    @bar = bar
  end
end
the Bar instance is passed to the constructor, so deleting the foo instance (explicitly or via the garbage collector), doesn't nescessarily kill the bar instance - this is aggregation. In ORM terms, if we had these tables for classes Foo and Bar:
BAR                FOO
+----+--------+      +----+~
| id | foo_id |      | id | 
+----+--------+      +----+~
| 42 | 69     |------| 69 |
~----~--------~      ~-----~

Then Bar *belongs_to* Foo because it's meaningless to keep a row (instance) of BAR lying around if the row in the FOO table reference by the foreign key `foo_id' no longer exists. So deletes in FOO cascade to BAR. Thus we say that Foo has a *composition* relationship with Bar.

Then consider the following:

BAR                FOO
~+----+      +----+--------+
 | id |      | id | bar_id |
~+----+      +----+--------+
 | 42 |------| 69 | 42     |
~-----~      ~----~--------+

Here we see that *has_one* is the reverse of *belongs_to* in that the foreign key would be kept in the FOO table, and deletes of FOO would not cascade to BAR.

Rating: 0

Rayman answered:

class HasOne < RefersTo end

Now the difference between BelongsTo and RefersTo is, as far as I can tell, the following:

a.belongs_to b
b.delete //Both got deleted since a.belongs_to b.

a.refers_to b
b.delete // a is still alive and kicking !

So it's about relation travelsal.

Rating: 0

capiCrimm answered:

I'm fairly sure it just describes ownership of the record.

If ORMA has_one ORMB, then ORMA has a field that contains the linked ORMB's. If ORMB belongs_to ORMA, then ORMB has a field that contains the linked ORMA's.

I'm guessing, and I might be wrong. :D

Rating: 0