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.