Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord: Pluck from multiple tables with same column name

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?

like image 968
Jshoe523 Avatar asked Oct 23 '15 16:10

Jshoe523


1 Answers

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")
like image 131
Pavan Avatar answered Sep 20 '22 22:09

Pavan