自动选择 ActiveRecord 中连接表的所有列的方法?
想知道升级到 Arel 后,ActiveRecord 是否支持自动方式从连接表中选择列,而无需在 select 子句中显式列出它们。
鉴于我将 users
表加入到 posts
,希望能够以更简洁的方式执行类似的操作:
scope :select_user,
select("posts.*, " + User.columns.map{|c|
"users.#{c.name} user_#{c.name}"}.join(','))
因此,我想自动选择字段来自用户,这样我就可以说
Post.joins(:user).select_user.first.user_name
Wondering with the upgrade to Arel, if ActiveRecord yet supports an automated way to select in the columns from joined tables, without having to explicitly list them in a select clause.
Given I'm joining the users
table to posts
, Would like to be able to do something like this in a more succinct manner:
scope :select_user,
select("posts.*, " + User.columns.map{|c|
"users.#{c.name} user_#{c.name}"}.join(','))
So, I want to automatically select the fields from user so that I get say
Post.joins(:user).select_user.first.user_name
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为如果您想在查询完成后访问关联的属性,那么您真正想要的是使用
includes
。因此,相同的查询将是这将导致两个查询,一个
select * from users
和一个select * from posts where posts.user_id in (id1, id2, id3...)< /code> (假设
post own_to user
)在特定情况下可能会影响性能,但从语法的角度来看可能是值得的。在某些情况下,它甚至可能更快Rails :include 与 :joins。如果您向查询添加限制运算符,Arel 还会智能地使用
join
,例如Post.includes(:user).where('users.name = "Bo Bob"') 将使用
join
执行一个查询,并且还使您能够在生成的Post
对象上使用关联。I think what you actually want here is to use
includes
if you want to access the association's attributes after the query is complete. So the same query would beThis will result in two queries, one
select * from users
and oneselect * from posts where posts.user_id in (id1, id2, id3...)
(assumingpost belongs_to user
) which may be a performance hit in a particular situation, but may be worth it from a syntax standpoint. In some cases it may even be faster Rails :include vs. :joins.Arel will also intelligently use a
join
if you add a restriction operator to the query e.g.Post.includes(:user).where('users.name = "Bo Bob"')
will do one query with ajoin
and also enable you to use the associations on the resultingPost
object.如果我正确理解你的问题,你可以使用 'joins':
或参数:
If I understand your question correctly, you can do it with 'joins':
or with a param: