I have a query like the following:
Author.select('authors.*, max(books.published_at) as last_publishing')
.joins(:books)
.group('authors.id')
This does what I want (returns a list of authors annotated with their most recent publishing date), but if I try to call count on this query, there is an issue.
SELECT COUNT(authors.*, max(books.published_at) as last_publishing)
AS count_authors_all_max_books_published_at_as_last_publishing, authors.id
AS authors_id FROM "authors"
INNER JOIN "books"
ON "books"."author_id" = "authors"."id"
GROUP BY authors.id
*** ActiveRecord::StatementInvalid Exception: PG::SyntaxError: ERROR: syntax error at or near "as"
LINE 1: ...COUNT(authors.*, max(books.published_at) as last_pu...
Obviously this is not the SQL I want to generate - I just want a SELECT COUNT(*) FROM ( ) myQuery.
I saw there was a similar issue with Rails 4 - has anyone else come up against this/is there a workaround? I can do query.to_a.size, but I would prefer to just be able to use the count method for my, and my coworkers, future sanity.
You should remove select temporary before call count
authors = Author.select('authors.*, max(books.published_at) as last_publishing')
.joins(:books)
.group('authors.id')
total_authors = authors.except([:includes]).count(:all)
Related
I'm running the following query in Rails 5, with the goal of finding the user with the most Pitches:
User
.select("users.*, COUNT(user_id) as pitch_count")
.unscoped
.joins("LEFT JOIN pitches AS pitches ON pitches.user_id = users.id")
.group("pitch.user_id")
.order("pitch_count DESC")
.limit(5)
But I'm getting the error:
Caused by PG::UndefinedColumn: ERROR: column "pitch_count" does not exist
Why isn't the query orderable by pitch_count?
Problem is in the unscoped method. It removes all previously defined scopes including select statement. See the following example:
User.select(:full_name, :email).unscoped.to_sql
# => SELECT "users".* FROM "users"
User.unscoped.select(:full_name, :email).to_sql
# => SELECT "users"."full_name", "users"."email" FROM "users"
See the difference? unscoped called after select definition completely removed every thing defined in the select.
For you this means that you should modify your code to call unscoped right after the model name:
User
.unscoped
.select("users.*, COUNT(user_id) as pitch_count")
.joins("LEFT JOIN pitches AS pitches ON pitches.user_id = users.id")
.group("pitch.user_id")
.order("pitch_count DESC")
.limit(5)
Note: new lines added mostly for readability but it should work like this in your ruby files. If you want to execute it in the rails console. You will have to remove new lines
Btw. you still might get error that column "user.id" must appear in the GROUP BY clause or be used in an aggregate function. It should be fixed by modifying group statement to use users.id instead of pitch.user_id:
.group("users.id")
I suggest you use counter_cache to make it easy to maintain and good for performance as well. By adding counter cache, you can get the user record with most pitches by User.reorder(pitches_count: :desc).first.
We have created a query on Rails with Postgres database, where we want courses to be in order by position as data available in an array, in our case it is course_ids.
A course_ids array contains courses' ids in squences.
Course.includes(:course_series).
where("course_id IN (?)", course_ids).
order("position(course_id::text in '?')", course_ids.join(',')).
order('course_name asc')
but it showing below error
ActiveRecord::StatementInvalid in FrontendController#get_courses
PG::InvalidColumnReference: ERROR: ORDER BY position 52 is not in select list
LINE 1: ...9)) ORDER BY position(course_id::text in '?'), 11,52, course...
^
: SELECT "at_courses".* FROM "at_courses" WHERE "at_courses"."deleted_at" IS NULL AND (course_id IN (52,11)) ORDER BY position(course_id::text in '?'), 52,11, course_name asc
Extracted source (around line #598):
Could you please share what went wrong here? Please go easy on me. I am not a technical guy.
Thanks!
Using active record query how do I do the following sql query?
sql = "select * from events
inner join places on events.place_id = places.id
inner join users on events.user_id = users.id"
where events.id = #{event_id}
I've tried
Event.joins(:user, :place).includes(:user, place).find(event_id)
This almost does what I want however does select events.* and not select .
I then tried
Event.joins(:user, :place).select('*.*')
This however returns an ActiveRelation object and I'm not sure how to get my results out of this.
I've also tried
Event.joins(:user, :place).find(event_id)
and this throws an error.
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near "."
Not sure what else to try. Is what I'm trying to do not possible?
Event.joins(:user, :place).where("events.id = ?", event_id).select("events.*, users.*, places.*")
I'm collecting the sale_stage of a group of Questions for display in my rails app view - which works fine provided I want them in alphabetical order (I don't):
#stages = Question.uniq.pluck(:sale_stage)
What I want is to select the same unique sale_stage names, but order them by question_id - as this would then display the stages in the right order on my page. I've tried using:
#stages = Question.order(:id).uniq.pluck(:sale_stage)
But this throws the following error:
SELECT DISTINCT "questions"."sale_stage" FROM "questions" ORDER BY "questions"."id" ASC
PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...estions"."sale_stage" FROM "questions" ORDER BY "questions...
^
: SELECT DISTINCT "questions"."sale_stage" FROM "questions" ORDER BY "questions"."id" ASC
Completed 500 Internal Server Error in 251ms
ActiveRecord::StatementInvalid (PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...estions"."sale_stage" FROM "questions" ORDER BY "questions...
^
: SELECT DISTINCT "questions"."sale_stage" FROM "questions" ORDER BY "questions"."id" ASC):
I'm not entirely sure what this means - and the answer for this StatementInvalid error don't help me much. Can anyone advise how to order this query by question_id please?
#stages = Question.order(:id).pluck(:sale_stage).uniq
I'm using postgresql for a database on a Rails app that keeps track of when certain events take place. The database column for when the event takes place is called when (bad name, I know). I can do this
#events = #group.events.order('created_at DESC')
However, when I do this
#events = #group.events.order('when DESC')
I get this error
PG::SyntaxError: ERROR: syntax error at or near "when"
LINE 1: ..."events" WHERE "events"."group_id" = $1 ORDER BY when DESC
^
: SELECT "events".* FROM "events" WHERE "events"."group_id" = $1 ORDER BY when DESC
A when record has this format in the database
when: "2013-08-07"
Based on what I've told you, can you see the reason why I can't do this
#events = #group.events.order('when DESC')
It's important for me to be able to order the events by when they are being held. Since ordering by created_at works, I don't see why the syntax error arises when I substitute a different column.
WHEN is a reserved word in SQL (think about the Switch cases: CASE <smth> WHEN ...)
You can try accessing it like this:
Event.order('events.when DESC')
You should change your column's name to something different than when (Take a look at #PhilipHallstrom comment)