# Replacing finder\_sql with named\_scope

**URL:** <https://www.ruby-forum.com/t/replacing-finder-sql-with-named-scope/179742>\
**Category:** Rails\
**Created:** [December 2, 2009, 11:45pm UTC](https://www.ruby-forum.com/t/replacing-finder-sql-with-named-scope/179742 "2009-12-02T23:45:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mrpunkin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/b5a626/32.png) [@mrpunkin](https://www.ruby-forum.com/u/mrpunkin)\
**Post date:** [December 2, 2009, 11:45pm UTC](https://www.ruby-forum.com/t/replacing-finder-sql-with-named-scope/179742/1 "2009-12-02T23:45:32Z")

</div>

I thought I would share a bit on here how I was able to use named\_scope  
to save me from an issue I was facing. I have a join model between Group  
and User, called GroupsUser. It is your standard join table containing  
the two foreign keys, as well as some additional information pertaining  
to that association such as if that user is an admin for that group, and  
if their membership has been accepted if it is a private group.

I needed a way to also look up photos in the group, but photos are only  
in the group because they belong to the user in the group. As you  
probably are aware, you are not able to chain up has\_many :through  
associations, and I already required one on Group for has\_many :users,  
:through=\>:groups\_users, and vice-versa. This meant I had (what I  
thought) only one option, to write SQL in the finder\_sql option for my  
:photos association on the Group model. I found out, however, very  
quickly that this would not allow me to still chain on additional Photo  
scopes as the finder\_sql is static, and thus appends its “select …” to  
any query it attempts to attach itself to, such as another named\_scope.

My solution? Use the same SQL that I would need to already write for  
finder\_sql, but split it into options in a named\_scope on the Photo  
model, and then call that scope from the group instance. This allows me  
to chain as many additional scopes or finders as I need without any SQL  
breakage. See below.

class Group \< ActiveRecord::Base  
has\_many :groups\_users, :dependent=\>:destroy  
has\_many :users, :through=\>:groups\_users

def photos  
Photo.in\_group(self)  
end  
end

class User \< ActiveRecord::Base  
has\_many :groups\_users  
has\_many :groups, :through=\>:groups\_users  
end

class GroupsUser \< ActiveRecord::Base  
belongs\_to :user  
belongs\_to :group  
end

class Photo \< ActiveRecord::Base  
belongs\_to :user

named\_scope :in\_group, lambda{|group| {  
:select=\>"`photos`.\*",  
:joins=\>“INNER JOIN `users` on `users`.id = `photos`.user\_id INNER  
JOIN `groups_users` ON `users`.id = `groups_users`.user\_id”,  
:conditions=\>["`groups_users`.group\_id = ?", group.id]  
}}  
end
