【问题标题】:How to validate the model, whether it is having particular column or not?如何验证模型,是否有特定的列?
【发布时间】:2021-01-11 08:55:44
【问题描述】:
class Project
  include Listable
       
  listtable(data_attribute: :verified_at)
end

关注

module Listable
  class_methods do
    def listable(data_attribute: :verified_at)
      raise ActiveModel::MissingAttributeError, 
        "Must have a verified_at attribute"  unless respond_to?(:verified_at)
    end
  end
end

在我的 项目模型我有专栏verified_at。如果我的表中没有verified_at 列,它应该会引发错误。

但在这里它没有正确响应。总是引发错误(即使是verified_at也存在)

预期

无论我在我的模型中包含这个问题,它都应该检查 verify_at 列是否存在。如果它不存在,应该引发错误。

这对我来说没有发生,请建议我任何解决方案,提前谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 activesupport-concern


    【解决方案1】:

    问题在于该模型没有像您预期的那样respond_to?

    Project.respond_to?(:id)
    # false
    

    为什么?因为您是在询问类本身是否具有 id 属性,该属性仅适用于实例。

    Project.first.respond_to?(:id)
    # true
    

    要解决此问题,您可以利用 Project.column_names 方法,如下所示。

    raise ActiveModel::MissingAttributeError, 
        "Must have a verified_at attribute" unless column_names.include?('verified_at')
    

    【讨论】:

      【解决方案2】:

      Listable 模块在这里并不是绝对必要的。 Rails 带有开箱即用的 ActiveRecord 验证,这样的东西可以满足您的需要:

      class Project
        validates :verified_at, presence: true
      end
      

      然后您可以实例化 Project 并检查它是否有效。如果.valid?返回false,则无法保存到数据库:

      project = Project.new
      => #<Project:0x00007ff3aec268a8
       id: nil,
       verified_at: nil,
       created_at: nil,
       updated_at: nil>
      project.valid?
      => false
      project.save!
      => ActiveRecord::RecordInvalid: Validation failed: Verified At can't be blank
      
      project = Project.new(verified_at: Time.zone.now)
      => #<Project:0x00007ff3aec268a8
       id: nil,
       verified_at: Mon, 11 Jan 2021 04:09:24 EST -05:00,
       created_at: nil,
       updated_at: nil>
      project.valid?
      => true
      project.save!
      #  DB query
      => true
      

      部分阅读:https://guides.rubyonrails.org/active_record_validations.html

      【讨论】:

      • 检查verified_at是否有值,问题是检查字段/列本身是否在数据库中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2013-05-21
      • 2011-09-20
      • 2018-04-17
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多