'How to call pluck with multiple table without using string params
If I have the following code:
User.where(users: {id: [1,2,3,4,5] } )
.joins("left outer join carts on users.id = carts.user_id)
.pluck("user.id", "user.name", "carts.id")
And this work fine. But I think it is cleaner if I can do something similar to the where clause like:
User.where(users: {id: [1,2,3,4,5] } )
.joins("left outer join carts on users.id = carts.user_id)
.pluck(users: [:id, :name], carts : [:id])
Is the second approach possible?
Also to note I know the left_joins method exists but I'm not using it here to make the example clear.
Solution 1:[1]
Second approach is not possible, look at the source:
# File activerecord/lib/active_record/relation/calculations.rb, line 183
def pluck(*column_names)
if loaded? && all_attributes?(column_names)
return records.pluck(*column_names)
end
if has_include?(column_names.first)
relation = apply_join_dependency
relation.pluck(*column_names)
else
klass.disallow_raw_sql!(column_names)
columns = arel_columns(column_names)
relation = spawn
relation.select_values = columns
result = skip_query_cache_if_necessary do
if where_clause.contradiction?
ActiveRecord::Result.new([], [])
else
klass.connection.select_all(relation.arel, nil)
end
end
type_cast_pluck_values(result, columns)
end
end
Solution 2:[2]
That hash syntax won't work - but if you want to avoid using strings you can use Arel to avoid hardcoding the table names:
users, carts = User.arel_table, Cart.arel_table
User.where(id: [1,2,3,4,5]) # you don't need to be specific if its on "this" models table
.joins("left outer join carts on users.id = carts.user_id")
.pluck(users[:id], users[:name], carts[:id])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | stolarz |
| Solution 2 | max |
