Skip to content

Instantly share code, notes, and snippets.

@Govan
Last active August 29, 2015 14:02
Show Gist options
  • Save Govan/4ca530ee3b1946bb74d4 to your computer and use it in GitHub Desktop.
Save Govan/4ca530ee3b1946bb74d4 to your computer and use it in GitHub Desktop.
class User
has_many :group_roles
has_many :groups, :through=>:group_roles
end
class GroupRole
belongs_to :user
belongs_to :group
end
class Group
has_many :group_roles
has_many :users, :through=>:group_roles
end
group_arel = Group.where(:active=>true).where(:important=>'very')
groups = group_arel.to_a # returns [group, group, group]
user_sql = group_arel.joins(:users).select("users.*").to_sql
User.find_by_sql(user_sql) # return [user, user, user] for all the users of all the groups on #17
# What I'd like to be able to do
user_arel = User.take_everything_but_the_select_from(group_arel)
amended_user_arel = user_arel.where(:name=>"bob")
amended_user_arel.to_a # returns [user, user, user]
@Govan
Copy link
Author

Govan commented Jun 16, 2014

The group_arel on #16 represents a complex query that, when finally executed, returns all the Groups that match. However, the same query can be used to return all Users of all matching Groups by changing the select clause, as shown on line 19-20, but that's returning an array so it's not possible to do any further chaining on the arel.

What I'd like to be able to do is change the 'class' of the query object to return instances of User rather than Group. Is this possible?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment