Belongs_to more than one model


#1

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?


#2

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.


#3

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…


#4

Sorry, bad example. I just wanted to know if i can have multiple
belongs_to
statements.

Thanks guys


#5

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