我有模型 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,您可以添加 filtered/partial index在 workout_id where is_creator = true
在事件记录级别,您可以添加 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
关于ruby-on-rails - Rails has_many :through validation nested records count by specific param,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36516471/