js111
js111

Reputation: 1314

Proper Rails association setup

Im setting up a reminder service that sends deals via email in relation to a persons interests AND city.. Basically, the user inputs important dates (friends bday, anniversary ect) and the interests of that special person.

I want to send them deals based on 1)the users city and 2)the interests of the related person

How should i setup my associations for the Deal model?

What i have so far..

class User < ActiveRecord::Base
belongs_to :city
has_many :person_interests, :as => :person
has_many :interests, :through => :person_interests

end

class City < ActiveRecord::Base
 attr_accessible :name 
  belongs_to :province
  has_many :users
end

class PersonInterest < ActiveRecord::Base 
  belongs_to :interest
  belongs_to :person, :polymorphic => true  
end

class Interest < ActiveRecord::Base
  has_many :person_interests
end

Thanks!

Upvotes: 0

Views: 71

Answers (1)

Larsenal
Larsenal

Reputation: 51186

If a deal could apply to more than one interest, you'd start with something like:

class Deal < ActiveRecord::Base 
  belongs_to :interests
  belongs_to :city
end

class City < ActiveRecord::Base
 attr_accessible :name 
  belongs_to :province
  has_many :users
  has_many :deals
end

class Interest < ActiveRecord::Base
  has_many :person_interests
  has_many :deals
end

And then you could do something like

@relevant_deals = @city.deals.where(:interest_id => 'abc')

or

@relevant_deals = @interest.deals.where(:city_id => 'def')

Upvotes: 1

Related Questions