On Apr 24, 6:06 am, Juan Pablo Avello <[email protected]> wrote:
> El martes, 24 de abril de 2012 03:56:21 UTC+2, Rafael C. de Almeida
> escribió:
> > Hello
>
> > I have two tables: Lawyer and Phone. Phone is separated into area code
> > and number. A lawyer has many phones. I want to produce a query which
> > searches for lawyers who have a phone matching a phone from a list of
> > phones.
> >     select * from phones where (area_code, number) in (('555',
> > '1234564'), ('533', '12345678'))
>
> > How to translate that to ActiveRecord?
>
> Your best option is probably:
>
> Lawyer.includes(:phones).where( :phones => {:area_code =>
> phone[:area_code], :number =>
> phone[:number]}) }
>
> Then you may iterate through phones at your will.
>
> Using .includes() preloads related models, phones in this case, and
> subsequent queries do not actually query the db but the data structure
> stored in memory (you can easily check this in a console; with .includes()
> no 'select *...' will appear on the logs when accessing a lawyer's phones)

That doesn't seem to work. First I tried the approach with joins:

1.9.3p194 :071 > lawyers = []
1.9.3p194 :071 > phones = [{area_code:'31', number:'32210412'},
{area_code:'32', number:'32210412'}]
1.9.3p194 :071 > phones.each { |phone| lawyers +=
Lawyer.joins(:phones).where(phones:phone) }
  Lawyer Load (1.0ms)  SELECT "lawyers".* FROM "lawyers" INNER JOIN
"phones" ON "phones"."lawyer_id" = "lawyers"."id" WHERE
"phones"."area_code" = '31' AND "phones"."number" = '32210412'
  Lawyer Load (0.4ms)  SELECT "lawyers".* FROM "lawyers" INNER JOIN
"phones" ON "phones"."lawyer_id" = "lawyers"."id" WHERE
"phones"."area_code" = '32' AND "phones"."number" = '32210412'

Then I tried it with includes:

    phones.each { |phone| lawyers +=
Lawyer.includes(:phones).where(phones:phone) }

includes' version was more verbose, but made two SQL queries as well.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to