-1

In rails 5 with Postgresql, I'm writing a scope to select Status items by date. My model is:

class Status < ApplicationRecord
  scope :in_month, ->(date){where("status_date = ?", date) if date.present?}
end

However, in rails console, I'm getting the following error when trying to use the scope. ```

2.4.0 :010 > Status.in_month("2018-06-01")
  Status Load (11.7ms)  SELECT  "statuses".* FROM "statuses" WHERE (status.status_date = '2018-06-01') LIMIT $1  [["LIMIT", 11]]
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "status"
LINE 1: SELECT  "statuses".* FROM "statuses" WHERE (status.status_da...
                                                    ^
: SELECT  "statuses".* FROM "statuses" WHERE (status.status_date = '2018-06-01') LIMIT $1

Note that for some reason, it's trying to access table "status", not "statuses".

What the heck am I doing wrong? This is pretty much straight out of the RailsGuide.

EDIT & "fix"

Humph... apparently the Rails console was in a bad state. I restarted the console after the comments below and found that my query worked perfectly. Note that the quotes are required for this format of the WHERE clause and that statuses is a correct pluralization of status.

And after restarting, the where(status_date: date) format described by praga2050 worked, as did the where("statuses.status_date = ?", date) suggested by Kedarnag Mukanahallipatna.

Lesson learned: reload! doesn't reload changes in models; you have to restart the console for Model changes to be recognized. See this SO answer: https://stackoverflow.com/a/5428421/446464

JESii
  • 4,678
  • 2
  • 39
  • 44

2 Answers2

-1

I think you missed the point of naming conventions in rails.

Model class names are singular, and will map automatically to the plural database table name.

According to this, you can change your model name to statuses.

Or set a table name to use in the rails model:

class Status < ApplicationRecord
  self.table_name = 'status'

  scope :in_month, ->(date) { where(status_date: date) if date.present? }
end
sfate
  • 155
  • 10
  • Well.. "statuses" is the plural of "status" and you can see that Rails correctly recognized that as the first part of their SQL statement is `SELECT "statuses".* FROM "statuses" WHERE...`. The pluralization failed in the WHERE clause. – JESii Aug 19 '18 at 11:05
-2

I am not sure why you are putting string inside the Where clause

scope :in_month, ->(date){where("status_date = ?", date) if date.present?}

Should be change like below.

Below one should work for you.

scope :in_month, ->(date){where(status_date: date) if date.present?}
praga2050
  • 729
  • 9
  • 18
  • The string format is explicitly described in the Ruby on Rails Guide (https://guides.rubyonrails.org/active_record_querying.html#scopes) section 14.2. Yours is an alternative approach and fails with the same error. – JESii Aug 19 '18 at 11:03