使用作用域检查相关模型在Rails中是否没有其他相关模型



我正在努力获得一个范围的工作。我在下面列出了简单的模型:

class User < ActiveRecord::Base
  has_many :authentications
  has_many :attendances
end
class Authentication < ActiveRecord::Base
  belongs_to :user
end
class Attendances  < ActiveRecord::Base
  belongs_to :user
end

我要做的是在考勤上写一个范围,检查没有身份验证的用户。类似以下语句:

scope :fulfilled_without_user_authentications, lambda { includes(:authentications).where('authentications.id' => nil) }

然而,出席率和认证之间显然不存在直接关系。

我是否应该创建这个链接(使用has many through),或者是否有一种方法可以在作用域本身中指定它。

也许你首先需要重新考虑你的关系。用户可以不经过身份验证就有考勤吗?

如果没有,我将重构你的关系为"has many through":

好的,所以我确定的方法是:

class User
  scope :with_authentications, where("id IN (SELECT user_id FROM authentications)")
  scope :without_authentications, where("id NOT IN (SELECT user_id FROM authentications)")
end
class Attendance
  scope :with_user_authentications, lambda {
    joins "INNER JOIN users ON users.id = attendances.attendee_id" and User.with_authentications
  }
  scope :without_user_authentications, lambda { 
    joins "INNER JOIN users ON users.id = attendances.attendee_id" and User.without_authentications
  }
end

EDIT

试试下面的方法,让我知道是否有效。

class Attendances  < ActiveRecord::Base
  belongs_to :user
  scope :fulfilled_without_user_authentications, lambda { joins(:user => :authentications).where('authentications.user_id != users.id') }
end

最新更新