Rails has_many :通过特定参数验证嵌套记录计数

Rails has_many :through validation nested records count by specific param

我有 Workout 和 User 模型,它们通过模型关联到多对多 用户锻炼。并且模型 UserWorkout 具有属性:is_creator,显示创建者是哪个用户。但是 Workout 应该只有一个创建者。添加此类验证的最佳方式是什么?

 class Workout < ActiveRecord::Base

  has_many :user_workouts, inverse_of: :workout, dependent: :destroy
  has_many :participants, through: :user_workouts, source: :user

  def creator
    participants.where(user_workouts: { is_creator: true }).order('user_workouts.created_at ASC').first
  end

end

class UserWorkout < ActiveRecord::Base

  belongs_to :user
  belongs_to :workout

end

class User < ActiveRecord::Base

  has_many :user_workouts, inverse_of: :user, dependent: :destroy
  has_many :workouts, through: :user_workouts

end

根据您的 DBMS,您可以在 workout_id where is_creator = true

上添加 filtered/partial index

在活动记录级别,可以添加一个custom validation

class UserWorkout
  validate :workout_has_only_one_creator

  private

  def workout_has_only_one_creator
    if self.class.find_by(workout_id: workout_id, is_creator: true)
      errors.add(:is_creator, 'can only have one creator')
    end
  end

首先,您的数据库结构存在设计缺陷。我认为 is_creator 不应该在 UserWorkout 中。这是 Workout

的责任

换句话说,Workout可以由一个用户创建,一个User可以创建多个Workout,所以它是User和[=之间的一对多关系13=]

Workout中保留一个created_by_id,并在其中添加一个关联。它将使很多事情变得更容易和更简单。

class Workout < ActiveRecord::Base

  has_many :user_workouts, inverse_of: :workout, dependent: :destroy
  has_many :participants, through: :user_workouts, source: :user

  belongs_to :creator ,  class_name: "User", foreign_key: "created_by_id"

end

并且不需要检查唯一性,因为它是 Workout

中的单个列

现在您不需要像每次需要查找锻炼创建者那样的复杂查询。这是一个简单的 belongs_to 关联。一切都会由 rails 处理:)