2011-09-28 49 views
1

我有以下类结构的应用程序,我从PHP移植到轨:的Rails 3.1的Active Record - 加载父对象中的has_many:通过关系

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_headers 
end 

我将如何加载MenuHeader或一个特定MenuItem的菜单?

像:

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

回答

2

您需要奇异的关联如下:

class MenuItem < ActiveRecord::Base 
    belongs_to :menu_header 
    has_one :menu, :through => :menu_header 
end 
+0

我需要menu_item_id添加到菜单表,因为关系已经在其他方向上存在? “@ mi.menu”和“@ mi.menus”似乎都没有这样做。 thx – timpone

+0

不,“through”选项意味着它会查看'menu'的'menu_header'关联。你可以仔细检查你的ID匹配在数据库中,我认为这应该工作。 –

+0

嗯....似乎没有工作。 MenuHeader是否需要'has_one'或是'belongs_to'是否足够? thx - 绝对是我的缺乏理解 – timpone

相关问题