Blandee Blandee - 2 years ago 76
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| "date"
t.string "name"
t.integer "cost"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"

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 ="%m")
@user = User.find(params[:id])
@expenses = Expense.where(:user_id =>, :date => month)

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 Source

Usually you can tackle it this way:

Expense.where(date: (

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download