Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pluck from an includes association when using STI?

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?

like image 825
DavidP6 Avatar asked Jan 20 '18 01:01

DavidP6


1 Answers

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
like image 76
Nathan Avatar answered Sep 30 '22 14:09

Nathan