Rails ActiveRecord: Pluck from multiple tables with same column name

痴心易碎 提交于 2019-12-10 15:09:44

问题


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?


回答1:


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")


来源:https://stackoverflow.com/questions/33306820/rails-activerecord-pluck-from-multiple-tables-with-same-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!