Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is it possible to pluck from multiple tables? #23

Open
axelson opened this issue Mar 4, 2017 · 3 comments
Open

Is it possible to pluck from multiple tables? #23

axelson opened this issue Mar 4, 2017 · 3 comments

Comments

@axelson
Copy link

axelson commented Mar 4, 2017

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?

@rasmar
Copy link

rasmar commented Jun 29, 2017

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.

@probablykabari
Copy link

@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.

@feliperaul
Copy link

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants