我现在正在做这个
class Enrollment < ApplicationRecord
belongs_to :user
validate :no_conflict
private
def no_conflict
user.enrollments.where.not(id: self).each do |e|
errors.add(:start_time, 'conflicts with another schedule') if true
end
end
end
class Availability < ApplicationRecord
belongs_to :user
validate :no_conflict
private
def no_conflict
user.availabilities.where.not(id: self).each do |a|
errors.add(:start_time, 'conflicts with another schedule') if true
end
end
end
由于两个模型中有相同的代码,我试图将其转移到这样的问题
class Enrollment < ApplicationRecord
include Schedulize
end
class Availability < ApplicationRecord
include Schedulize
end
module Schedulize
extend ActiveSupport::Concern
included do
belongs_to :user
validate :no_conflict
end
private
def no_conflict
user.<???>.where.not(id: self).each do |x|
errors.add(:start_time, 'conflicts with another schedule') if true
end
end
end
我不确定如何让模块调用包含它的类方法(问号在上面)。有人可以帮我指出正确的方向
最佳答案
你可以这样做:
def no_conflict
user.send(self.class.table_name).where.not(id: self).each do |x|
errors.add(:start_time, 'conflicts with another schedule') if true
end
end
self.class.table_name
将按照约定返回注册
和可用性
。如果模型和表名称中的关系有不同的名称,您可以尝试不同的名称。
关于ruby-on-rails - 如何调用模块中的类特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569334/