2012-07-31 27 views
1

我有以下关系:发现通过其与用户相关联用的has_many所有记录

user.rb

has_many :ownerships 
has_many :restaurants, :through => :ownerships 

restaurant.rb

has_many :ownerships 
has_many :users, :through => :ownerships 

我也有一个菜单模型belongs_to :restaurant

很明显,menuuser之间没有直接联系,除非您通过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 

除其他事项外,但似乎没有任何工作。我总是正确地得到菜单的无效菜单'undefined method'。

我正在考虑制作一个循环,通过每个restaurant并添加menu附加到它,但我不是100%确定如何在menu控制器内如何做到这一点。

回答

1

如果添加一个新的关联到user模式是这样的:

class User 
    has_many :menus, :through => :restaurants 

当您执行current_user.menus,它会自动从你的用户餐馆获取所有菜单。希望能帮助到你。

+0

太棒了!那就是诀窍。谢谢! – FilmiHero 2012-07-31 20:01:04

相关问题