Rails 3: Merge scopes

dets. 17th, 2012 | Filed under Programming

I run into a case where I had User.search method and I wanted the GroupMember model be searchable by the user’s attributes. The most DRY way to accomplish this in Rails 3 is to merge scopes. In the User model:

NB! It’s important to have the User’s field names fully qualified so that they won’t be applied to the GroupMember table. And in the GroupMember model:

Now it’s possible to search for GroupMembers by the User attributes:

This results in SQL query:

Be Sociable, Share!
Tags: ,
No comments yet.