简单的模型关系问题

时间:2011-08-12 20:27:24

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

我有四个名为user,school,subscription和news_item的rails模型。我的情况是用户订阅学校以获得该学校的新闻通知,如何显示用户订阅的所有news_items。

我的用户模型有这个

  belongs_to :school
  has_many :schools, :through => :subscriptions
  has_many :subscriptions

  def subscribe_to(school)
    subscribe = subscriptions.build(:school_id => school.id)
    if !subscribe.save
      logger.debug "you have already subscribed to '#{school.name}'"
    end
  end

after_create:create_school_subscription       def create_school_subscription         school = self.school_street         self.subscriptions.build(:school_id => school.id)       端

我的订阅模式有

  belongs_to :user
  belongs_to :school, :class_name => 'School'
  validates_uniqueness_of :school_id, :scope => :user_id
  validates_presence_of :user_id, :school_id

我的学校模型已经

  has_many :users
  has_many :news_items

最后我的news_item模型已经

belongs_to :school

完成所有这些后,如何才能获得用户通过学校订阅的所有新闻

2 个答案:

答案 0 :(得分:2)

class NewsItem
  scope :news_for, lambda { |user|
    {
        :joins      => "INNER JOIN subscriptions on news_items.school_id = subscriptions.school_id",
        :conditions => "subscriptions.user_id = #{user.id}"
    }
  }
end

NewsItem.news_for(User.first)

答案 1 :(得分:0)

如果您想要用户所有学校的所有新闻项目,那么:

usr.schools.map{|s| s.news_items}.flatten

如果您只想要用户所属学校的所有新闻项目,那么:

usr.school.news_items
祝你好运! :)