【问题标题】:Proper Rails association setup正确的 Rails 关联设置
【发布时间】:2012-06-19 16:48:10
【问题描述】:

我正在设置一个提醒服务,通过电子邮件发送与个人兴趣和城市相关的交易。基本上,用户输入重要日期(朋友生日、周年纪念日等)和那个特别的人的兴趣。

我想根据 1)用户所在城市和 2)相关人员的兴趣向他们发送交易

我应该如何为 Deal 模型设置关联?

到目前为止我有什么..

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

谢谢!

【问题讨论】:

  • 到目前为止你有什么?什么不起作用或对您来说似乎不理想?
  • @rfunduk 添加了我已有的内容。一切都很好,收集我需要的信息也很好。只是想知道如何将新交易模型与兴趣和城市联系起来。
  • 交易会是兴趣和城市的belongs_to吗?

标签: ruby-on-rails ruby-on-rails-3 associations


【解决方案1】:

如果一项交易可能适用于多个兴趣,您可以从以下内容开始:

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

然后你可以做类似的事情

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

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

【讨论】:

  • 谢谢!我真的不在乎交易是否可以属于一个以上的兴趣......任何更容易设置的......我不介意让管理员多次添加一个交易,如果它需要与多个兴趣相关联......
  • 那么它如何在城市和利益模型上工作......例如,在城市 (a) 中可以有兴趣交易 (a) 而在城市 (b) 中将会有不同的利息交易 (a)
  • 我需要对兴趣模型做些什么吗?
  • 一个城市有多个交易吗?如果是这样,是的,你需要 has_many。我将在兴趣模型上添加相同的想法。这是同一个概念。
  • 哦,好的,谢谢.. 是的,每个城市都有针对每个兴趣的交易(用户在注册期间选择的 20 个预填充列表)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多