过滤字段值上的has_many关联

时间:2012-01-12 09:10:15

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

我有两种模式:

class Event < ActiveRecord::Base
  belongs_to :destination
end

class Destination < ActiveRecord::Base
  has_many :events
end

我的“事件”模型有一个“激活”(布尔)字段,我想在我调用Destination.events时只显示激活的事件。我怎样才能总是过滤激活的字段?

2 个答案:

答案 0 :(得分:4)

使用:conditions选项:

class Destination < ActiveRecord::Base
  has_many :events, :conditions => { :activated => true }
end

答案 1 :(得分:1)

可能性为default_scope,例如default_scope where('activated = 1')

请参阅http://apidock.com/rails/ActiveRecord/Base/default_scope/class