ruby-on-rails - 如何调用模块中的类特定方法

标签 ruby-on-rails ruby activerecord

我现在正在做这个

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/

相关文章:

javascript - "Uncaught SyntaxError: Unexpected token <"尝试在 Javascript 中使用 Rails 数组的内容

javascript - 计算数据客户端还是服务器端更快?

ruby-on-rails - 如何在 Rails 功能测试中调用不同的帖子到不同的 Controller

ruby-on-rails - rails : undefined method `primary_key' for String:Class

ruby-on-rails - Rails 不保存已更改的属性

ruby-on-rails - ActiveRecord 关联

ruby-on-rails - 乘客未在 80 端口启动

ruby-on-rails - Rails created_at 查找条件

ruby - wicked_pdf 找不到 libv8-3.16.14.3(但已安装)

ruby - 遍历 ruby​​ (jekyll) 中的哈希数组