Rails Model Relationship: Has one but also belongs to many

Posted by Lowgain on Stack Overflow See other posts from Stack Overflow or by Lowgain
Published on 2010-04-13T21:05:02Z Indexed on 2010/04/13 21:13 UTC
Read the original article Hit count: 412

Filed under:
|
|
|
|

I have two Models, Modela and Modelb.

Modela can only own one Modelb, but Modelb can be a part of many Modela's.

What I have right now is

class Modela < ActiveRecord::Base
  has_one :modelb
end

class Modelb < ActiveRecord::Base
  belongs_to :modela, :foreign_key => "modela_id" #might not make sense?
end

Not too sure about the whole :foreign_key thing I was doing there, but it was where it was when I left off. As I am trying to allow Modelb to be part of many Modela's, I don't want to add a modela_id field to the Modelb table.

What is the best way to do this?

© Stack Overflow or respective owner

Related posts about rails

Related posts about model