I have the following models using Single Table Inheritance (STI) in Rails 4:
class User < ActiveRecord::Base
has_many :notes
end
class Item < ActiveRecord::Base
end
#inherits from Item
class Folder < Item
belongs_to :folder
end
#inherits from Item
class Note < Item
belongs_to :folder
end
I would like to perform the following query which should pluck the id of a note and the name of the folder that it belongs to.
user = User.first
user.notes.includes(:folder).pluck(:id, :'folders.name').first
This returns the following error:
ERROR: missing FROM-clause entry for table "folders"
Since notes and folders both inherit from Item, there is just one items table and I cannot make it pluck from the includes folder.
If I do:
user = User.first
user.notes.includes(:folder).pluck(:id, :'items.name').first
It returns the name of the note and not the folder that is belongs to (because both Note and Folder inherit from Item and are in the items table). Is there some way to pluck from the folder that has been included and not the note?
Under the hood, SQL has to reference the same table twice. Therefore it has two different names in the query. You need to figure out what name Rails is using for the second reference.
Use user.notes.joins(:folder).to_sql
to figure out what table name to use.
It's probably something like folders_items
, so perhaps try this:
user.notes.joins(:folder).pluck(:id, 'folders_items.name').first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With