Rails 3.1 Active Record - loading the parent object in a has_many :through relationship
I have the following class structure for an app I'm porting from php to rails:
class Menu < ActiveRecord::Base
has_many :menu_headers
has_many :menu_items, :through => :menu_headers
end
class MenuHeader < ActiveRecord::Base
acts_as_tree :parent_id
has_many :menu_items
belongs_to :menu
end
class MenuItem < ActiveRecord::Base
belongs_to :menu_heade开发者_如何学运维rs
end
How would I load the MenuHeader or Menu for a specific MenuItem?
Like:
ruby-1.9.2-p290 :004 > @b=Menu.find(1) #works
ruby-1.9.2-p290 :005 > @b.menu_headers #works
ruby-1.9.2-p290 :006 > @b.menu_items #works
ruby-1.9.2-p290 :004 > @mi=MenuItem.find(1) #works
ruby-1.9.2-p290 :005 > @mi.menu_headers #doesn't work
ruby-1.9.2-p290 :006 > @mi.menus #doesn't work
thx
You need singular associations as follows:
class MenuItem < ActiveRecord::Base
belongs_to :menu_header
has_one :menu, :through => :menu_header
end
精彩评论