开发者

Determining intersection of two HABTM relationships in rails 3

I have the following relationships:

class Article < ActiveRecord::Base
has_and_belongs_to_many :required_certs, :class_name=>"Certification"
...
end

class User < AR::B
has_and_belongs_to_many :certifications
...
end

I'd like to be able to find all users that have the same certifications as an article. So if an article had certs A and B, and User had A, B, C, D, that user would be returned. Users with just A or just B would not be. So in essence, something like

User.joins(:certifications).where('certifications.id IN (?)', @article.required_certs.collect{|c| c开发者_如何学编程.id})

Instead of using the IN operator though, I think I'd have to use AND because I only want users who have ALL of the specified certs.

I'm stumped so any help would be much appreciated!

Thanks


This is how I did it, am open to more elegant solutions though!

@certs = @article.required_certs.collect{|c| c.id}
User.all(:joins=>:certifications, 
         :group=>User.attributes_for_sql, 
         :select=>'users.*', 
         :conditions => ['certifications.id in (?)', @certs], 
         :having=> "count(*)=#{@certs.length}")

Hope this helps someone!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜