Ruby on Rails: How to validate a model without Active Record?
Asked Answered
D

2

22

I'm currently trying to validate fields without having an ActiveRecord::Base inheritance.

My model stores the data on a cache server so I do not need ActiveRecord.

Anyway, I would like to validate the fields of the model like I would if I was using ActiveRecord (e.g validates_numericality_of :quantity, :greater_than => 0) ?

How can I do that?

Damalis answered 22/3, 2012 at 5:20 Comment(1)
I believe this is that question: https://mcmap.net/q/265861/-rails-model-without-databaseSibyl
F
33

In Rails 3, Active Model contains the non-database functionality of Active Record.

Basically, you need to include ActiveModel::Validations, define your fields as attr_accessor, use an initialize method to initialize the attributes and make them non-persisted as your model isn’t persisted to a database.

This way you can have validations on the tableless model and your controller the same as if you were using Active Record. There's also a Railscast on this http://railscasts.com/episodes/219-active-model.

Flaunch answered 22/3, 2012 at 5:38 Comment(1)
For Rails 4+ follow this SO questionMauldon
L
1

Check out our Veto gem instead if you're looking for a standalone validations for ruby objects. It's lightweight, and has no dependencies.. ActiveModel might be overkill.

Lacerta answered 6/11, 2013 at 21:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.