Rails ActiveRecord:从多个具有相同列名的表中抽签 [英] Rails ActiveRecord: Pluck from multiple tables with same column name
问题描述
我有一个简单的用例:
用户有很多推文
推文属于用户
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)
每个表都有一个created_at列,但是上面的结果返回了tweet的created_at。我还如何选择用户的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
那么如何通过使用pluck做到这一点?
So how can I do this by using pluck?
推荐答案
您可以执行以下操作
@tweets = Tweet.includes(:user).all.pluck(:created_at, "users.created_at")
而且 .all
在这里不是必需的,因为加入/包含
获取所有 记录/相关记录 。因此,最终查询如下所示:
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")
这篇关于Rails ActiveRecord:从多个具有相同列名的表中抽签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!