Reputation: 31
I have a model:
class Entry < ActiveRecord::Base
belongs_to :organization
belongs_to :detail_organization, class_name: "Organization"
end
and:
class Organization < ActiveRecord::Base
has_many :entries
end
I can successfully:
> entry = Entry.last.detail_organization
Entry Load (0.5ms) SELECT "entries".* FROM "entries" ORDER BY "entries"."id" DESC LIMIT $1 [["LIMIT", 1]]
Organization Load (0.3ms) SELECT "organizations".* FROM "organizations" WHERE "organizations"."id" = $1 LIMIT $2 [["id", 69], ["LIMIT", 1]]
=> #<Organization:0x007fcabcabc
id: 69,
name: "Detail Office",
code: "DFO",
classification_id: 4,
active: true,
created_at: Thu, 05 Jan 2017 21:49:48 UTC +00:00,
updated_at: Thu, 05 Jan 2017 21:49:48 UTC +00:00>
but I've been working on a query that returns a rather large dataset being exported to xls requiring plucking. I've tried:
[111] pry(main)> @entries = Entry.scheduled_between(start_date, end_date).pluck('detail_organization.name')
(0.6ms) SELECT detail_organization.name FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2) [["calendar_date", "01/06/2017"], ["calendar_date", "01/06/2017"]]
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "detail_organization"
LINE 1: SELECT detail_organization.name FROM "entries" INNER JOIN "d...
^
: SELECT detail_organization.name FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2)
from /Users/atfreeme/.rvm/gems/ruby-2.3.3/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/postgresql_adapter.rb:598:in `async_exec'
with and without including the related organization table, but can't seem to make the association with pluck.
Interestingly enough:
[112] pry(main)> @entries = Entry.scheduled_between(start_date, end_date).pluck('detail_organization_id')
(0.6ms) SELECT "entries"."detail_organization_id" FROM "entries" INNER JOIN "daily_logs" ON "daily_logs"."id" = "entries"."daily_log_id" WHERE ("daily_logs"."calendar_date" BETWEEN $1 AND $2) [["calendar_date", "01/06/2017"], ["calendar_date", "01/06/2017"]]
=> [60, 60, 69]
at least gets me ids.
Anyone with any pluck advice or possibly a new direction if I'm hopefully being descriptive enough about the problem? Not sure if this is PostgreSQL or ActiveRecord as an issue.
Upvotes: 1
Views: 330
Reputation: 23671
The problem is with your query
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "detail_organization"
ActiveRecord is trying to search table detail_organization
but you dont have the table in your database
you should query with organizations
table as detail_organization
is just an association name not a table name
@entries = Entry.scheduled_between(start_date, end_date).joins(:detail_organization).pluck('organizations.name')
Upvotes: 3