Passionate Engineer
Passionate Engineer

Reputation: 10412

Use Rails model without database interaction

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.

Upvotes: 1

Views: 4170

Answers (2)

tihom
tihom

Reputation: 8003

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

Upvotes: 4

Rails Guy
Rails Guy

Reputation: 3866

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

Upvotes: 0

Related Questions