Em 13-08-2012 21:49, Rafael Almeida escreveu:
On Sunday, August 12, 2012 12:06:00 AM UTC-3, Matt jones wrote:
On Aug 11, 2012, at 6:23 PM, Rafael Almeida wrote:
> On Friday, August 10, 2012 5:50:58 PM UTC-3, EMoreth wrote:
> Try this:
>
> Project.joins(:services).where(:services => { :id => [1,2]
}).group(:id).having("count(*) = 2").all
>
> This produces to me:
>
> "SELECT `projects`.* FROM `projects` INNER JOIN `services` ON
`services`.`project_id` = `projects`.`id` WHERE `services`.`id` IN
(1, 2) GROUP BY id HAVING count(*) = 2"
>
> Which returns me only the projects who are associated to both
services 1 and 2.
>
> Indeed that does the trick. Nice thinking. It's probably even
better than the intersection approach from SQL point of view.
>
> Anyway, the reason we don't have & and | operators in
activerecord is that it's believed that there's always a better
way to write a query not using them?
I'd say it's more that it's phenomenally difficult to come up with
a *generic* method that will transform (for instance) your two
queries:
Person.joins(:services).where('services.type' => 1)
Person.joins(:services).where('services.type' => 2)
into the final query. Note that the suggestion above is only
correct if you never have Project with two links to the same
service. Based on the what you've described about your domain,
this is probably a sensible assumption - but the general case
wouldn't necessarily be able to assume that.
I get you now. I have studied activerecord internals a little bit more
and I figure there'd need to be a major rewrite to support it. For
one, if you have
(Person.joins(:services).where('services.type' => 1)
& Person.joins(:services).where('services.type' => 2)).where(:name =>
'John')
we'd need to keep track that "where(:name => 'John')" should be
applied to the subquery, while the other where's should be used to
create the subqueries. Right now it seems like arel doesn't even
support "where" on unions and intersections. q1.intersect(q2) returns
an Intersection object which doesn't have any query methods.
I'd really urge you to evaluate Sequel instead of rewriting Arel. Sequel
already supports queries like those and much more complex ones and it is
well tested. Maybe it would be much easier to adapt Sequel to AR API
than to try to rewrite the Sequel advanced features in Arel...
--
You received this message because you are subscribed to the Google Groups "Ruby on
Rails: Core" 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-core?hl=en.