【问题标题】:Has_Many_Through & Active_Record_Collection_Proxy ERRORHas_Many_Through & Active_Record_Collection_Proxy 错误
【发布时间】:2017-09-14 21:02:47
【问题描述】:

我是 Rails 新手,正在做我的第一个小项目

我的 rails 应用中有 3 个模型:

餐厅

菜单

Items

我在设置关联时遇到了问题,而且似乎无法正确设置。我的模型如下:

 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

当我尝试通过调用我得到的类来呈现页面上的部分视图时 "

用于#的未定义方法“items” 菜单::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

我花了很多时间尝试调整关联,但没有成功。谢谢。

【问题讨论】:

  • 可能在您的 if 语句中。您正在调用@menus,但您只想调用一个@menu 来获取该特定菜单的项目。如果您实际上有多个menus,那么您应该遍历它们,然后为menu 的每个实例调用.items。在这种情况下,您的 render @items 可能应该是 render @menu.items,因为从这个角度来看,它看起来不像定义了 @items
  • 餐厅控制器 = def show @menus = Menu.where(:restaurant_id => @restaurant.id) end

标签: ruby-on-rails database activerecord rails-activerecord model-associations


【解决方案1】:

尝试使用 :menu 代替 :menus

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    相关资源
    最近更新 更多