Rails关联 - 多种模型能力

时间:2014-02-26 18:43:35

标签: ruby-on-rails associations

我有以下用户可以创建简报,也可以订阅简报。有没有更好的方法来区分这两种能力与关联,或者我可以按照以下建议将所有权放在订阅模型中:multiple has_many associations in Rails。通过此解决方案,我如何编写简报模型以获取简报所有者和简报订阅者。

 Newsletter Model
  # fields: id, user_id
  has_many :subscriptions
  has_many :users, through: :subscriptions 
  belongs_to :user *i.e. created by a single user*

 Subscription Model
  # fields: user_id, newsletter_id
  belongs_to :newsletter
  belongs_to :user

 User Model
  # fields: id
  has_many :subscriptions
  has_many :newsletters, through: :subscriptions
  has_many :newsletters *i.e. created many newsletters*
  has_many :created_newsletters, :through => :subscriptions, *old answer*
           :source => :newsletter, 
           :conditions => ["newsletter.creator = ?", true]

1 个答案:

答案 0 :(得分:2)

Newsletter Model
  has_many :subscriptions
  has_many :subscribers, through: :subscriptions, source: :user 
  belongs_to :creator, class_name: "User", foreign_key: "user_id"

 Subscription Model
  # fields: user_id, newsletter_id
  belongs_to :newsletter
  belongs_to :user

 User Model
  # fields: id
  has_many :subscriptions
  has_many :subscribed_newsletters, through: :subscriptions, source: :newsletter
  has_many :created_newsletters, class_name: "Newsletter", foreign_key: "user_id"

现在,您可以通过

获得订阅者和创建者
newsletter.subscribers
newsletter.creator