recursive_acronym
recursive_acronym

Reputation: 3031

activerecord / db theory - where do I put these fields?

I have the models shown below. I need to store some details that are specific a person and a house (first_viewed:date, opening offer:decimal, etc). I feel like these should belong to the PersonHouse model but I'm not certain enough. Any suggestions?

class Person < ActiveRecord::Base
  has_many :houses, through: :person_houses
  has_one :favorite_house, through: :person_houses     
end

class PersonHouse < ActiveRecord::Base
  belongs_to :house
  belongs_to :person
end

class House < ActiveRecord::Base
  has_many :house_people
  has_many :people, through: :person_houses
end

I could do something like this to get all the details but perhaps there is a more effient way.

@house = House.find(1)
@house.house_people.each do |hp|
  puts hp.person.name
  puts hp.first_viewed
  puts @house.address
end

Upvotes: 0

Views: 56

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

I think your assumption is correct. If the data is relevant to the relationship between a person and a house, then yes it belongs on this model. The only recommendation I would make is to rename this model to a name that better describes what the relationship is. It doesn't have to be the concatenation of the two models it joins. I don't know exactly what the model is going to be ultimately used for, but SelectedHouse, HouseProspect or something along those lines might work.

You can also delegate properties to the house or person models:

class PersonHouse < AR::Base
  belongs_to :person
  belongs_to :house

  delegate :address, :to => :house, :prefix => true
  delegate :name, :to => :person, :prefix => true
end

person_house.address
person_house.person_name

Upvotes: 1

Related Questions