2013-08-16 22 views
0

我需要獲取不在:through條件中的記錄。activerecord記錄不在:through條件中

我有3個表:

class A < ActiveRecord::Base 
    has_many :B_A 
    has_many :B, through: :B_A 
end 
class B < ActiveRecord::Base 
    has_many :B_A 
    has_many :A, through: :B_A 
end 
class BA < ActiveRecord::Base 
    belongs_to :A 
    belongs_to :B 
end 

我得到全A通過listOfA = B.A鏈接到一個特定的B,而我也需要得到所有A沒有任何B.我該怎麼辦?

回答

0

好的,我有兩個條件放入我的連接查詢。 我的MySQL是:

select a.`id`, a.`label` 
from `A` a 
left join `BA` ba 
on a.`id` = ba.`a` 
where a.`uid`='userId' 
and ba.`a` is null 

我的ActiveRecord的是現在:

A.select(['A.id', :label]) 
    .joins('left outer join B_A on B_A.a_id = A.id') 
    .where({ user_id: current_user.id, "B_A.a_id" => nil }) 

我有我的所有A不是BA

相關問題