2012-05-23 55 views
1

我有這個我如何做一個LEFT JOIN在軌找到

User.joins(:notifications).joins(:company_users).joins(:role_users).where("notifications.id = ? AND role_users.role_id != '1' AND (company_users.company_id = ? OR users.company_id = ?)", notification.id, p.company_id, p.company_id) 

=> []

產生這個SQL

SELECT `users`.* FROM `users` 
INNER JOIN `subscriptions` ON `users`.`id` = `subscriptions`.`user_id` 
INNER JOIN `notifications` ON `notifications`.`id` = `subscriptions`.`notification_id` 
INNER JOIN `company_users` ON `company_users`.`user_id` = `users`.`id` 
INNER JOIN `role_users` ON `role_users`.`user_id` = `users`.`id` 
WHERE (notifications.id = 1 
AND role_users.role_id != '1' 
AND (company_users.compcany_id = 67 OR users.company_id = 67)) 

問題是我需要離開加入company_users,不知道如何實現在軌道上

我知道我可以用find_by_sql做到這一點,我聽說這不是真的像軌道....任何想法

+0

你有'has_one:company_user'或'has_many:company_users'關聯嗎? – PinnyM

+0

我解決了它......看看我的答案......並回答你的問題,它是多對多的,儘管company_user – Trace

回答

9

解決

User.joins(:notifications).joins("LEFT JOIN `company_users` ON `company_users`.`user_id` = `users`.`id`").joins(:role_users).where("notifications.id = ? AND role_users.role_id != '1' AND (company_users.company_id = ? OR users.company_id = ?)", notification.id, p.company_id, p.company_id) 
0

類用戶<的ActiveRecord :: Base的

has_many :friends, :foreign_key=>"u_from",:class_name=>"Friend" 

類朋友<的ActiveRecord :: Base的

belongs_to :user 

朋友= user.friends.where(:u_req_status => 2).joins( 「LEFT OUTER JOIN用戶ON users.u_id = friends.u_to」)選擇(「friend_id,u_from,u_to,u_first_name。 ,u_last_name,u_email,u_fbid,u_twtid,u_picture_url,u_quote「)