pluck_to_hash icon indicating copy to clipboard operation
pluck_to_hash copied to clipboard

Is it possible to pluck from multiple tables?

Open axelson opened this issue 7 years ago • 3 comments

Say I have the following schema:

User has many Post Post has many Comment Comment belongs to EmailAddress

I can easily do Post.where(user_id: user_id).pluck_to_hash which will get me all the fields of the Post. But what if I want to also get the fields of the Comments and EmailAddresses as well?

axelson avatar Mar 04 '17 02:03 axelson

You can try something like Post.joins([:comment]).where(user_id: user_id).pluck_to_hash(:first_post_column, :second_post_column, "comments.first_column as comments_first_column", "comments.second_column as comments_second_column") same thing apply to deeper nested EmailAddress . Join that table as well and retrive fields.

rasmar avatar Jun 29 '17 10:06 rasmar

@axelson pluck actually takes any valid SQL, so you can do .pluck('table.id, other_table.some_column'). This should work with this gem as well.

probablykabari avatar May 11 '18 15:05 probablykabari

@RipTheJacker is correct. Also, you can alias the keys for a better result. For instance:

User.left_joins(properties: :location).distinct.limit(100).pluck_h("users.id as users_id", "locations.city as city")

Returns an array of: {"users_id"=>2, "city"=>"Curitiba"}

This way, pluck_s (to Struct) also works flawlessly, because otherwise you would have structs with users.id methods on them, which would only be callable if you used .send("users.id"), which would defeat the point.

feliperaul avatar May 05 '20 06:05 feliperaul