Belongs_to more than one model

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?

On 3/22/06, Vincent G. [email protected] 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.

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…

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

Thanks guys

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs