Rails中模型之间的链范围

时间:2016-03-19 07:15:42

标签: sql ruby-on-rails

我在Rails中的模型之间查询时遇到了一些麻烦。我有Message的课程belongs_to: booking。我的目标是将active范围添加到Message,取决于Booking范围。

class Booking < ActiveRecord::Base
  has_one :event
  has_many :messages

  def self.active
    includes(:event).
      where('events.endtime >= ? AND status IS NOT ?'
            Time.current.beginning_of_week,            
            statuses['canceled'])
  end
end

class Message < ActiveRecord::Base
  belongs_to :booking
  belongs_to :person

  self.active(person_id)
    where(person_id: person_id).merge(Booking.active)
  end
end

我想找到Message指向特定Person的关联Bookingactive的{​​{1}}。因此,我希望在创建Booking.active时使用Message.active

使用上述实现调用Message.active(1)会返回以下错误:

Association named 'event' was not found on Message; perhaps you misspelled it?

我是否可以在Booking.active的实施中使用Message.active并返回获取Message

1 个答案:

答案 0 :(得分:1)

如果您要为关联添加条件,您还需要加入,而不仅仅是mergeinclude,即以下内容应该有效:

class Booking < ActiveRecord::Base
  # ...
  def self.active
    joins(:event).
      where('events.endtime >= ? AND status IS NOT ?'
          Time.current.beginning_of_week,            
          statuses['canceled'])
  end
end

class Message < ActiveRecord::Base
  # ...
  self.active(person_id)
    where(person_id: person_id).joins(:booking).merge(Booking.active)
  end    
end

关于此的文档不​​多,请参阅this以获取更多信息。