如何在rails中找到左连接

时间:2012-05-23 14:30:06

标签: ruby-on-rails ruby ruby-on-rails-3 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上保持联接并且不确定如何在rails中实现它

我知道我可以通过find_by_sql来做到这一点,我听说这不是真正的轨道......任何想法

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

class User<的ActiveRecord ::基

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

类朋友<的ActiveRecord ::基

 belongs_to :user

friends = user.friends.where(:u_req_status => 2).joins(“LEFT OUTER JOIN users ON users.u_id = friends.u_to”)。select(“friend_id,u_from,u_to,u_first_name,u_last_name, u_email,u_fbid,u_twtid,u_picture_url,u_quote“)