1

Listing Model

  belongs_to :listable, polymorphic: true
  belongs_to :car, -> { where(listings: {listable_type: 'Car'}) }, foreign_key: 'listable_id'

  def car
     return unless listable_type == "Car"
     super
  end



listing = Listing.first
listing.car

Error

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "listings") LINE 1: ....* FROM "cars" WHERE "cars"."id" = $1 AND "listings"... ^ : SELECT "cars".* FROM "cars" WHERE "cars"."id" = $1 AND "listings"."listable_type" = $2 LIMIT $3

I also tried:

  belongs_to :car, -> {  joins(:listings).where(listings: {listable_type: 'Car'}) }, foreign_key: 'listable_id'

and I got:

ActiveRecord::ConfigurationError (Can't join 'Car' to association named 'listings'; perhaps you misspelled it?)

What is causing this error?

Roman Alekseiev
  • 1,854
  • 16
  • 24
user2012677
  • 5,465
  • 6
  • 51
  • 113
  • rather than `super` just call `listable` this will return your `Car`. The belongs_to is wrong because the `where` clause applies to the `Car` model (thus the error). To solve that you would need to `join(:listings)` and drop the where I believe – engineersmnky Jul 26 '19 at 17:14
  • @engineersmnky, Thank you! It's related to this question, in case it changes your answer.. https://stackoverflow.com/questions/57209650/eager-load-relation – user2012677 Jul 26 '19 at 17:19
  • However you overlooked [this comment](https://stackoverflow.com/questions/16123492/eager-load-polymorphic#comment60786136_16124295) which suggests similar to what I have however it appears they recommend `-> { joins(:listings).where(listings: {listable_type: 'Car'}) }` which makes little sense to me because the join should already enforce that on a polymorph e.g. `INNER JOIN listings ON listings.listable_id = cars.id and listings.listable_type = 'Car'` So I am still not sure that is needed. I never use polymorphs in this fashion otherwise I would post an answer. – engineersmnky Jul 26 '19 at 17:32
  • @engineersmnky, I tried your note, but got the above error too. Thank you for trying. If you have other thoughts, please let me know. I am about ready to through my computer out the window – user2012677 Jul 26 '19 at 17:41
  • Well, Car has_one :listing, does anything need to be adapted? – user2012677 Jul 26 '19 at 18:00
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/197060/discussion-between-user2012677-and-engineersmnky). – user2012677 Jul 26 '19 at 18:03

0 Answers0