2012-07-31 61 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

相關問題