khiav223577 / deep_pluck

Allow you to pluck attributes from nested associations without loading a bunch of records.
MIT License
460 stars 14 forks source link

has_and_belongs_to_many issue #41

Closed TaylorMerritt closed 3 years ago

TaylorMerritt commented 3 years ago

I'm not sure if it's possible to do so, but I'm having an issue using deep_pluck with a has_and_belongs_to_many association.

Example data structure:

class County < ApplicationRecord
  has_and_belongs_to_many :zip_codes
end
class Zipcode < ApplicationRecord
  has_and_belongs_to_many :counties
end

When I try to use deep_pluck on this association I get the following:

[2] pry(main)> County.limit(2).deep_pluck(zipcodes: :city)
   (1.2ms)  SELECT counties.id FROM "counties" LIMIT 2
   (4.3ms)  SELECT counties_zipcodes.county_id, "zipcodes"."city" FROM "zipcodes" WHERE "counties_zipcodes"."county_id" IN (178, 179)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "counties_zipcodes"
LINE 1: SELECT counties_zipcodes.county_id, "zipcodes"."city" FROM "...

So it appears to be using the correct joins table for the SELECT and WHERE, but not the FROM.

TaylorMerritt commented 3 years ago

I am able to work around this setting up the has_and_belongs_to_many manually:

class County < ApplicationRecord
  has_many :counties_zipcodes
  has_many :zipcodes, through: :counties_zipcodes
end
class Zipcode < ApplicationRecord
  has_many :counties_zipcodes
  has_many :counties, through: :counties_zipcodes
end
class CountiesZipcode < ApplicationRecord
  belongs_to :county
  belongs_to :zipcode
end
[19] pry(main)> County.limit(2).deep_pluck(zipcodes: :city)
   (0.4ms)  SELECT counties.id FROM "counties" LIMIT 2
   (4.6ms)  SELECT counties_zipcodes.county_id, "zipcodes"."city" FROM "zipcodes" INNER JOIN "counties_zipcodes" ON "counties_zipcodes"."zipcode_id" = "zipcodes"."id" WHERE "counties_zipcodes"."county_id" IN (178, 179)
[
    [0] {
        :zipcodes => [
            [ 0] {
                "city" => "Alpine"
            },
...
khiav223577 commented 3 years ago

Thanks for your report. I'm going to take a look at it.

TaylorMerritt commented 3 years ago

Thank you!

khiav223577 commented 3 years ago

Hi, @taylor-au I just released deep_pluck v1.1.8 The issue should be fixed in this version. 😃

For more details, see the changelog.

TaylorMerritt commented 3 years ago

It is working correctly for me. Thank you very much @khiav223577 !