1

Is there a way to use Rails model for validation only without interaction with the database?

Would I generate model using console and use it with Active Record validations?

I'm trying to use it to validate a CSV import, use Model validations, process then output back in another CSV format.

This is done without database interaction but I thought for validation, using Model would be a good way to be less error prone.

2 Answers 2

4

Look into ActiveModel

E.g. specifically for validations (taken from the above docs)

class Person
  include ActiveModel::Validations

  attr_accessor :first_name, :last_name

  validates_each :first_name, :last_name do |record, attr, value|
    record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
  end
end

person = Person.new
person.first_name = 'zoolander'
person.valid?  # => false
Sign up to request clarification or add additional context in comments.

Comments

0

Yes you can do this, Lets suppose you have a Person class, than you can do this:

class Person

  attr_accessor :name, :age

  include ActiveRecord::Validations
  include ActiveModel::Validations

  validates_presence_of :name
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.