How to validate the model, whether it is having particular column or not?

Viewed 100
class Project
  include Listable
       
  listtable(data_attribute: :verified_at)
end

Concern

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

In my project model i am having column verified_at. if i am not having verified_at column in my table it should raise the error.

But here it is not responding properly. always raising the error(even the verified_at is present also)

Expected

Wherever i am including this concern in my model, it should check the verified_at column is present or not. If it is not present, should raise the error.

It is not happening for me, Please suggest me any solution, Thanks in advance

2 Answers

The problem is that the model doesn't respond_to? in the way you expected it to do.

Project.respond_to?(:id)
# false

why? because you are asking the class itself if it has the id attribute, that only works on an instance.

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

To work around this you can take advantage of the Project.column_names method, like this.

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

The Listable module isn't strictly necessary here. Rails comes with ActiveRecord validations out of the box, something like this will do what you need:

class Project
  validates :verified_at, presence: true
end

You can then instantiate a Project and check if it is valid. If .valid? returns false, it cannot be saved to the Database:

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

Some reading: https://guides.rubyonrails.org/active_record_validations.html

Related