开发者

In Ruby on Rails, how do I query for items that have no associated elements in a has_many :through relationship

I have a Contact model, and a User model, and a join table and each 开发者_运维问答is HABTM more or less.

How can I query for the Contacts that have no users assigned to them? Driving me nuts.

Thanks


IMHO you should do a raw SQL query something along the lines of....

select c.*
from   contacts c left join contacts_users cu on c.id = cu.contact_id
where  cu.contact_id is null

I don't know of any pretty ORM-specific way to do it. Obviously you'll want to tailor the query to use the actual fields from your table.


I believe this thread is looking for the same thing right?

Want to find records with no associated records in Rails 3

If I understand you correctly, then I think it could be something like:

Contact.includes(:jointablenames).where( :jointablenames => {:contact_id => nil } )
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜