使用包含或左外连接来实现复杂的嵌套关联

时间:2015-05-04 09:17:17

标签: ruby-on-rails-4 activerecord left-join

我有四个模特

class Company < ActiveRecord::Base
  has_many :share_types
  belongs_to :user
end
class ShareType < ActiveRecord::Base
  has_many :shares
  belongs_to :company
end
class Share < ActiveRecord::Base
  belongs_to :user
  belongs_to :share_type
end
class User < ActiveRecord:Base
 has_many :companies
 has_many :shares
end

现在,current_user或用户拥有公司的所有公司的名单都有这样的公司股票。

Company.joins(share_types:[:shares]).where("shares.user_id=? OR companies.user_id=?", @user.id, @user.id)

但是左外连接另一个我不知道如何使用包含或条件另一个提示是

Company.includes(share_types:[:shares]).where(shares:{user_id: @user.id} OR companies:{user_id: 1})

我该怎么做。

1 个答案:

答案 0 :(得分:0)

我可以在参考文献的帮助下获得我期望的结果。这是我的查询,只是张贴以帮助其他人。

Company.includes(share_types:[:shares]).where("shares.user_id=? OR companies.user_id=?", 1,1).references(:shares)

其工作归功于Obie Fernandez的The Rails 4 Way