1

I have a model Expense.rb, in which a user has many. New expenses can be added through an ajax form and thus I have the appropriate files setup (create.js.erb, destroy.js.erb.. etc)

Currently when a new expense is submitted via the remote form, an amount sum is also updated in the create.js.erb, which in my Expense model looks like this:

def total_value
    Expense.sum(:amount)
end

create.js.erb:

$('#total').html('$<%= number_with_delimiter(@expense.total_value) %>');

The problem is this sums all expenses from the database whereas I need to just find for the current_user (which I know is not accessible from the model).

Inside my controller, on the index action I'm doing it like so:

@expenses = current_user.expenses
    @total_value = @expenses.sum(:amount)

which means I can fetch it for the current_user in my index view by just doing: <%= number_with_delimiter(@total_value) %>

but as for the create action:

def create
    @expense = Expense.new(secure_params)
    @expense.user = User.find(current_user.id)
    @expense.save
    respond_to do |format|
      format.html { redirect_to index_expense_path }
      format.js
    end
  end

I'm not sure how to go about passing the current_user to total_value in the model in order to sum just for the current_user id in total_value which is used in the create js.erb.

Jon Girard
  • 245
  • 1
  • 4
  • 15

3 Answers3

5

Expense.sum(:amount) takes all the expense records out.

Changing

def total_value
    Expense.sum(:amount)
end

to:

def self.total_value
    sum(:amount)
end

would call self, so doing

current_user.expenses.total_value 

should work, and if you do Expense.total_value will still keep working.

Giannis
  • 813
  • 7
  • 13
0

The problem is this sums all expenses from the database whereas I need to just find for the current_user (which I know is not accessible from the model).

Perhaps you could use a scope & pass the user id to it:

#app/controllers/expenses_controller.rb
def total_votes
   Expense.user(current_user).sum(:amount)
end

#app/models/expense.rb
Class Expense < ActiveRecord::Base
    scope :user, ->(user) { where(user_id: user.id) }
end
Richard Peck
  • 76,116
  • 9
  • 93
  • 147
0

Don't you need a total_expenses method in your User model:

Class User

  has_many :expenses

  def total_expenses
    expenses.sum(:amount)
  end
end

Then you can just call

current_user.total_expenses 
Chris Lewis
  • 1,315
  • 10
  • 25