【问题标题】:Finding all records associated with User with a has_many through association通过关联查找与具有 has_many 的用户关联的所有记录
【发布时间】: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 模型。

很明显,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:NilClass, which I understand; I'm not getting to themenus` 的undefined methodmenus'。

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

【问题讨论】:

    标签: ruby-on-rails session collections controller


    【解决方案1】:

    如果您像这样向user 模型添加新关联:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      相关资源
      最近更新 更多