Daniel Bailey
Daniel Bailey

Reputation: 115

Adding a date to a date attribute in active record

I am trying to add a date of birth to each patient in my database and having issues adding a date to the dob attribute on each patient. When I add for ex. Patient.first(dob: "01/25/1990") I get an error reading no implicit conversion of Integer into Hash. Any ideas on how I would do so?

 create_table "patients", force: :cascade do |t|
    t.string "first_name"
    t.string "last_name"
    t.integer "age"
    t.date "dob"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

When I seeded my database, my dob field was nil

I have also tried Patient.first(dob: Date.parse('31-12-2010')) and still get the same error.

Upvotes: 0

Views: 510

Answers (1)

mu is too short
mu is too short

Reputation: 434585

You have two problems:

  1. first doesn't take query arguments.
  2. Your date format is ambiguous.

The first finder method looks like:

first(limit = nil)
Find the first record (or first N records if a parameter is supplied). If no order is defined it will order by primary key.

You want to use find_by as your .where(...).first shortcut.

And to avoid ambiguity with your dates, you should use Date objects or ISO-8601 formatted strings (i.e. YYYY-MM-DD) inside the application and leave the supposedly "human friendly" formats for the very edges.

You want to say:

Patient.find_by(dob: '1990-01-25')

Upvotes: 2

Related Questions