Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

Thank you very much for your help.

like image 499
Nicolas Guillaume Avatar asked Mar 22 '12 05:03

Nicolas Guillaume


People also ask

What does .save do in Ruby?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


2 Answers

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.

like image 121
prasvin Avatar answered Sep 18 '22 16:09

prasvin


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.

like image 41
Erik Lott Avatar answered Sep 19 '22 16:09

Erik Lott