Reputation: 2243
I have an Entry model which belongs to an Organization model...twice.
class Entry < ActiveRecord::Base
belongs_to :organization
belongs_to :temp_organization, class_name: "Organization"
end
I'm trying to write a single AR query that pulls off the associated organization and temp_organization name using pluck
.
Entry
.includes(:organization, :temp_organization)
.pluck('organizations.name', 'temp_organizations.name')
This crashes with the following error:
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "temp_organizations"
Which makes sense - there is no temp_organizations
table since that association is managed through the regular organizations
table.
How do I get pluck
to pull the temp_organization name?
Upvotes: 2
Views: 484
Reputation: 421
Try using,
Entry
.includes(:organization, :temp_organization)
.references(:organization, :temp_organization)
.pluck('organizations.name', 'entries_temp_organizations.name')
Upvotes: 2
Reputation: 768
So with multiple joins to the same table, AR does some magic and renames the table, which is why you can't pull up the right table name.
You can check what the table name is by looking at the generated sql:
Entry.includes(:organization, :temp_organization).to_sql
You should get something like:
...INNER JOIN \"organizations\" \"entries_temp_organizations\" ON \"entries_temp_organizations\"...
I would suspect the table name is 'entries_temp_organizations' (following AR rule of alphabetical ordering for join tables). A pluck with the correct table name should do the trick.
Upvotes: 1