0

我是新来的铁轨和我的工作我的第一个小项目Has_Many_Through&Active_Record_Collection_Proxy错误

我有3种型号在我的Rails应用程序:

餐厅< - (主模型)

菜单< - (直接关系到餐厅,餐厅只能有1个菜单)

项目< - (直接关系到菜单,菜单有很多项目)

我在设置关联时遇到问题&看起来似乎无法正确对待。我的模型如下:

class Restaurant < ApplicationRecord 
    has_one :menu 
    has_many :items, through: :menus 

class Menu < ApplicationRecord 
    belongs_to :restaurant 
    has_many :items 


class Item < ApplicationRecord 
    belongs_to :menu 

当我尝试通过调用类在页面上呈现的局部视图我得到 “

未定义的方法'项目的# 菜单:: ActiveRecord_Associations_CollectionProxy :0x3a74d08>

我敢这样做:

 <%= render @menus%> 
     <%= render @items %> 

我已成功显示MENU部分,但显示项目会抛出未定义的方法错误。

这里是我的餐厅控制器:

def show 
    @menus = Menu.where(:restaurant_id => @restaurant.id) 
    @items = Item.where(:menu_id => @menus.id) 
    end 

我花了很多时间尝试,没有运气,调整关联。谢谢。

+0

可能会在你的if语句。您正在调用'@ menus',但您只想调用一个'@ menu'来获取该特定菜单的项目。如果你实际上有多个'menus',那么你应该遍历这些菜单,然后为'menu'的每个实例调用'.items'。在这种情况下,你的'render @ items'应该可以是'render @ menu.items',因为从这里看起来'@ items'没有被定义。 – user3366016

+0

显示您申报的地方@menus –

+0

Restaurant Controller = def show @menus = Menu.where(:restaurant_id => @ restaurant.id)end –

回答

0

尝试:菜单代替:菜单

class Restaurant < ApplicationRecord 
    has_one :menu 
    has_many :items, through: :menu