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 2006-03-23 04:57
on 2006-03-23 05:07
On 3/22/06, Vincent G. <firstname.lastname@example.org> 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.
on 2006-03-23 05:46
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...
on 2006-03-23 09:36
Sorry, bad example. I just wanted to know if i can have multiple belongs_to statements. Thanks guys
on 2006-03-23 18:50
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