【发布时间】:2012-07-29 16:03:46
【问题描述】:
我有以下关系:
user.rb
has_many :ownerships
has_many :restaurants, :through => :ownerships
restaurant.rb
has_many :ownerships
has_many :users, :through => :ownerships
我还有一个 belongs_to :restaurant 的 Menu 模型。
很明显,menu 和 user 之间没有直接联系,除非您通过 restaurant。
我试图让它只显示由user 创建的菜单。
通过这种方法,我只能显示当前登录用户创建的餐厅:
restaurants_controller.rb
class RestaurantsController < ApplicationController
# GET /restaurants
# GET /restaurants.json
def index
if current_user.has_role? :admin
@restaurants = Restaurant.all
elsif current_user.has_role? :user
@restaurants = current_user.restaurants
end
end
如何在我的 menus 控制器下通过 restaurant 执行相同的操作?
我试过了:
@menus = current_user.restaurants.menus
和
@menus = current_user.restaurants.each.menus
除其他外,但似乎没有任何效果。我总是正确地得到 nil:NilClass, which I understand; I'm not getting to themenus` 的undefined methodmenus'。
我正在考虑创建一个循环,遍历每个 restaurant 并添加附加的 menu,但我不能 100% 确定如何在 menu 控制器中执行此操作。
【问题讨论】:
标签: ruby-on-rails session collections controller