使用has_many通过关联查找与User关联的所有记录

时间:2012-07-31 19:38:17

标签: ruby-on-rails session collections controller

我有以下关系:

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

除此之外什么似乎都没有用。我总是正确获取nil:{IilClass undefined method菜单的, which I understand; I'm not getting to the菜单。

我正在考虑制作一个遍历每个restaurant的循环并添加附加到它的menu,但我不能100%确定如何在menu控制器中执行此操作。

1 个答案:

答案 0 :(得分:1)

如果您向user模型添加新关联,请执行以下操作:

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

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