pluck_to_hash
pluck_to_hash copied to clipboard
Is it possible to pluck from multiple tables?
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?
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.
@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.
@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.