如何调用模块中的 class 特定方法
How to call a class specific method in a module
我正在做这个
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
我不确定如何让模块调用包含它的 class 方法(问号在上方)。有人能帮我指明正确的方向吗
你可以这样做:
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
将 return enrollments
& availabilities
按照惯例。如果模型中的关系名称与 table 名称不同,您可以尝试不同的名称。
我正在做这个
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
我不确定如何让模块调用包含它的 class 方法(问号在上方)。有人能帮我指明正确的方向吗
你可以这样做:
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
将 return enrollments
& availabilities
按照惯例。如果模型中的关系名称与 table 名称不同,您可以尝试不同的名称。