Automatic way to select all columns of a joined table in ActiveRecord?

The surprise is upgrading to Arel if ActiveRecord still supports the automatic way to select columns from joined tables without having to explicitly list them in the select clause.

Given that I am joining the table usersto posts, I would like to do something like this in a more concise way:

  scope :select_user,
    select("posts.*, " + User.columns.map{|c| 
      "users.#{c.name} user_#{c.name}"}.join(','))

So, I want to automatically select fields from the user to get a response

Post.joins(:user).select_user.first.user_name
+3
source share
2 answers

I think you really want to use it here includesif you want to access the attributes of the association after completing the request. The same request will be

Post.includes(:user).first.user.name

: select * from users select * from posts where posts.user_id in (id1, id2, id3...) ( post belongs_to user), , . Rails: include vs.: join.

Arel join, , . Post.includes(:user).where('users.name = "Bo Bob"') join, Post.

+3

, "join":

class Post < ActiveRecord::Base
  belongs_to :user

  scope :select_user, joins(:user).where('users.name = "Mary"')
  ...
end

:

class Post < ActiveRecord::Base
  belongs_to :user

  scope :select_user, lambda {|user_name|
    joins(:user).where('users.name = ?', user_name)
  }
  ...
end
+1

All Articles