I have a simple use case:
User has many Tweets Tweet belongs to User
And i'm trying to pluck a column name that exists on both tables. For example:
@tweets = Tweet.includes(:user).all.pluck(:created_at)
Each table has a created_at column, but the result from above returns the created_at for the tweet. How can I also pluck the user's created_at?
My workaround is below utilizing joins and selects:
@tweets = Tweet.joins(:user).select("users.created_at AS created_date").all
So how can I do this by using pluck?
You can do the below
@tweets = Tweet.includes(:user).all.pluck(:created_at, "users.created_at")
And also .all
is not necessary here as joins/includes
fetch all records/associated records. So the final query would be like below
@tweets = Tweet.includes(:user).pluck(:created_at, "users.created_at")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With