Can I test on a form element that is not part of the model?

So, I have a registration form, and part of it is billing / credit card information. This information is stored and processed by a third-party application, so the data is not stored in our database.

So, how can I run elements through validates_ methods in Rails? ( validates_presence_of , validates_length_of , etc.)

Or am I going to check in the wrong place for these elements?

+4
source share
3 answers

You can create a dummy model to facilitate your form information. There is no need to save models in the database.

Just create a new file in the application / models and you will go very well.

example: app / models / ccinfo.rb

 class Ccinfo < ActiveRecord::Base attr_accessor :card_type, :card_number, :pin, :exp_month, :exp_date, :card_holder, ... validates_presence_of :card_holder ... end 

If the form is based on a different model, you can simply move the insides of the specified model into a model form based on the same effect.

Can you check without saving by calling valid? method. Throw errors, as with any other model, if they are valid? returns false. Otherwise, continue processing.

0
source

For future readers who use Rails3, check out the ActiveModel:

 require 'active_model' class Place include ActiveModel::Validations validates_presence_of :name attr_accessor :name end 
+1
source

Yes, I think it’s possible to do it.

eg

  class User < ActiveRecord::Base attr_accessor :card_number validates_presence_of :card_number end 

You need to create an attribute in the model itself, and then apply validation to it.

You can also write your own accessor that sends data to a third party like this.

  class User < ActiveRecord::Base attr_accessor :card_number validates_presence_of :card_number def card_number=(number) ..... end end 
0
source

All Articles