如何跨has_many / through关系调用范围

时间:2012-08-20 13:19:01

标签: ruby-on-rails-3 activerecord

我有以下内容(在RoR 3.1和MySQL 5.1上):

  class Menu < ActiveRecord::Base
    has_many :menu_headers
    has_many :menu_items, :through => :menu_headers
    belongs_to :location      
  end

  class MenuHeader < ActiveRecord::Base
      acts_as_tree :parent_id
      has_many :menu_items
      belongs_to :menu
  end

  class MenuItem < ActiveRecord::Base
    scope :is_enabled, where(:is_enabled => true)
    belongs_to :menu_header
  end

我希望能够在整个关系中调用范围;像这样的东西:

  # call the scope :is_enabled here
  Menu.find(12).(where menu_items.is_enabled)

但不知道该怎么做。

我想要的行为:

  Menu.find(12)

继续拉动menu_items,其中is_enabled = false

关于如何做到这一点的任何想法?

THX

编辑#1 添加了act_as_tree和位置关联,因为这些也需要工作。

Scope with join on :has_many :through association这样的东西可能会起作用,但看起来有点难看

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

Menu.find(12).menu_items.is_enabled

它将返回与ID为12的菜单相关联的所有已启用的menuitem。