0

感谢另一个问题的一些帮助,我现在有一个嵌套资源设置,它几乎可以按照我需要的方式工作。这是关于控制器的后续问题。

费用既有用户,也有他们所属的项目。

我想访问/projects/5/expenses,并查看该项目的所有费用列表(正在运行),但它对当前登录的用户也很敏感,所以他们只能看到自己的花费。

首先是模型:

class Expense < ActiveRecord::Base
  attr_accessible :amount, :project_id, :user_id

  belongs_to :project
  belongs_to :user

end

其他每个模型都有“has_many :expenses”,以完成关系。

所以我的路线看起来像:

  resources :projects do
    resources :expenses
  end

class ExpensesController < ApplicationController

    def index
      @user = current_user  
      @project = Project.find(params[:project_id])
      @expense_list = @project.expenses.all  
end

如何通过仅显示 current_user 的费用来进一步过滤我的@expense_list?

4

1 回答 1

2

You need a an additional condition to query the expenses based on the user that they belong to. I would suggest that you create a scope in your Expense model

scope :for_user, lambda{ |user| 
      where( :user_id => user.id )
   }

And you can do this in the controller:

@expense_list = @project.expenses.for_user(current_user).all  
于 2012-11-06T18:47:41.873 回答