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.

Full support for 'or' is a similar problem - there's a first-draft here:

https://github.com/rails/rails/pull/6817

but that code isn't going to work correctly for anything but fairly similar 
queries; joins, selects, etc all go out the window.

--Matt jones

-- 
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 rubyonrails-core@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-core+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to