Abid
Abid

Reputation: 7227

Rails 3 Active Record Fetch associated model based on scope

I have been struggling with this for a whole day now.

Here is what I have. A User model and an Address model. User has_many :addresses and Adddress belongs_to :user.

Now I want to search for users whose email contains a give term, or one of the users's addresses contains that term. So lets say the term is 'jap', any User whose email like '%jap%' or any user whose any address city or address_line is like '%jap%' should be returned.

I can get the Users with a simple join like this

users = User.joins('LEFT OUTER JOIN addresses ON users.id=addresses.user_id').where('users.email like '%jap%' OR addresses.city like '%jap%' OR addresses.address_line like '%jap%')

This gives me the desired users. What I want is that with the returned user I also want those addresses that matched the criteria.

If after the above I do

users.first.addresses

It will give me all of the that user's addresses. I know I can by doing another query on that user's addresses like this

users.first.addresses.where( addresses.city like '%jap%' OR addresses.address_line like '%jap%')

But that isnt how it should work. I have tried includes and googled about it but havn't found a solution yet. Any one ever came across this ???

Edit#1: there are many similar solutions with 2 queries, What I am after is a single query solution, because to me it doesn't make sense to apply the same conditions on addresses twice.

Upvotes: 2

Views: 287

Answers (1)

kwbock
kwbock

Reputation: 647

Could you use a named scope on the address model similar to the following ?

named_scope :city_or_line_like, lambda { |str| {
    :conditions => ['conditions here']
}}

That way you could do users.first.addresses.city_or_line_like('arg')?

Upvotes: 1

Related Questions