Blandee Blandee - 7 months ago 21
Ruby Question

How to show entries from the current month?

For the sake of explanation, I'm writing an app where a User can log their expenses.

In the User's show view, I want to only show the User's expenses from the current month.

My expenses table looks like this:

create_table "expenses", force: :cascade do |t|
t.date "date"
t.string "name"
t.integer "cost"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
end


The date field is in the date format, so looks like:
Thu, 14 Apr 2016


In my controller, I've got something like:

def show
month = Date.today.strftime("%m")
@user = User.find(params[:id])
@expenses = Expense.where(:user_id => @user.id, :date => month)
end


Obviously, this isn't going to work, but it will be something along these lines, I'm guessing?

Any help would be great, thanks!

Answer

Usually you can tackle it this way:

Expense.where(date: (Date.today.beginning_of_month..Date.today.end_of_month))

Where that defines a range that can be used as a BETWEEN x AND y clause.

If this is a common operation you might want to express the date as a separate column in YYYYMM format so that these are easily retrieved.