Thanks to some help in another question, I now have a nested resource setup, and it is nearly working the way I need it to. This is a follow-up question about the controller.
Expenses have both a user, and a project that they belong to.
I would like to visit /projects/5/expenses, and see a list of all the expenses for that project, (which IS working), but also have it sensitive to the user that is currently signed in, so they only see their own expenses.
first the models:
class Expense < ActiveRecord::Base
attr_accessible :amount, :project_id, :user_id
belongs_to :project
belongs_to :user
end
each of the other models has “has_many :expenses”, to complete the relationship.
so my route looks like:
resources :projects do
resources :expenses
end
And
class ExpensesController < ApplicationController
def index
@user = current_user
@project = Project.find(params[:project_id])
@expense_list = @project.expenses.all
end
How can I filter my @expense_list further by only showing the current_user’s expenses?
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
And you can do this in the controller: