timpone
timpone

Reputation: 19979

How to call a scope across a has_many / through relationship

I have the following (on RoR 3.1 and 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

I'd like to be able to call the scope across the relationship; something like this:

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

but not sure how to do this.

I'd like the behavior for:

  Menu.find(12)

to continue to pull menu_items where is_enabled=false

Any ideas on how to do this?

thx

edit #1 added the act_as_tree and location associations as these also need to be working.

Something like this Scope with join on :has_many :through association might work but seems a little bit ugly

Upvotes: 0

Views: 383

Answers (1)

Matzi
Matzi

Reputation: 13925

This should do the trick:

Menu.find(12).menu_items.is_enabled

It will return all enabled menuitem associated with the menu with id 12.

Upvotes: 1

Related Questions