Thursday, April 28, 2011

ruby on rails has_one question

Hello,

I am trying to understand has_one relationship in ruby on rails.

let's say I have two models - Person and Cell

class Person < ActiveRecord::Base
  has_one : cell
end

class Cell < ActiveRecord::Base
  belongs_to : person
end

can I just use has_one: person instead of belongs_to : person in Cell model?

isn't it same?

From stackoverflow
  • Using both allows you to get info from both Person and Cell models.

    @cell.person.whatever_info and @person.cell.whatever_info.
    
  • If you add "belongs_to" then you got a bidirectional association. That means you can get a person from the cell and a cell from the person.

    There's no real difference, both approaches (with and without "belongs_to") use the same database schema (a person_id field in the cells database table).

    To summarize: Do not add "belongs_to" unless you need bidirectional associations between models.

  • No, they are not interchangable, and there are some real differences.

    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. So has_one can ONLY go in a class that is referenced by a column in another table.

    So this is wrong:

    class Person < ActiveRecord::Base
      has_one :cell # the cell table has a person_id
    end
    
    class Cell < ActiveRecord::Base
      has_one :person # the person table has a cell_id
    end
    

    So is this:

    class Person < ActiveRecord::Base
      belongs_to :cell # the person table has a cell_id
    end
    
    class Cell < ActiveRecord::Base
      belongs_to :person # the cell table has a person_id
    end
    

    For a two-way association, you need one of each, and they have to go in the right class. Even for a one-way association, it matters which one you use.

    Pablo Fernandez : Nice answer. Seeing your answer I realize I read half the question. I'm sorry, but glad that you jumped in. + 10
    Sarah Mei : I've had to look this up a billion times. I wish they had thought through the naming a little better, to make it more clear which one goes where.
    y0mbo : Great, now I know the two wrong answers. Would be better to show the "correct" way to show it. Just sayin'.

0 comments:

Post a Comment