Forum: Ruby on Rails belongs_to more than one model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Vincent G. (Guest)
on 2006-03-23 04:57
(Received via mailing list)
Suppose I have one table:

states
    id
    statename

And I have two other tables that contains states:

houses
    id
    color
    state_id

places
    id
    place_name
    state_id

How would my model relationships look like?

class State < ActiveRecord::Base
    belongs_to house
    belongs_to place
end

class House < ActiveRecord::Base
    has_one state
end

class Place < ActiveRecord::Base
    has_one state
end

Is that right?  Can I have a model that belongs to multiple models?
Wilson B. (Guest)
on 2006-03-23 05:07
(Received via mailing list)
On 3/22/06, Vincent G. <removed_email_address@domain.invalid> wrote:
>     color
>     belongs_to house
>
> Is that right?  Can I have a model that belongs to multiple models?
>

You can have as many belongs_to associations as you want in one model,
but you don't want that with the table structure you sketched out.

The ActiveRecord setup you want is probably:
class State < ActiveRecord::Base
  has_one :place
  has_one :house
end

class Place < ActiveRecord::Base
  belongs_to :state
end

class House < ActiveRecord::Base
  belongs_to :state
end

Put "belongs_to :name" in the class that wraps a table containing a
"name_id" column.

--Wilson.
Daniel -. (Guest)
on 2006-03-23 05:46
(Received via mailing list)
That should probably be
class State <ActiveRecord::Base
   has_many :places
   has_many :houses
end

Unless you only want one house and one place per state...
Vincent G. (Guest)
on 2006-03-23 09:36
(Received via mailing list)
Sorry, bad example.  I just wanted to know if i can have multiple
belongs_to
statements.

Thanks guys
Richard W. (Guest)
on 2006-03-23 18:50
(Received via mailing list)
Is it correct to say that the has_one relations are not necessary unless
you are going to be reading the state table and want to get all the
houses that are in that state?

I.e. state.houses
This topic is locked and can not be replied to.