Using Rails form helpers on non-existent methods

Normally, when using form helpers in Rails, each field directly
correlates to a method on the appropriate object.

However, I have a form (user signup) that needs to include fields that
are not part of the user model itself (for instance, card details) but
need to appear.

How can I build the form so that I can get the necessary fields, and
validate them as I need to (so that it fits with all my other
validations) without dirty-ing my user model?

Essentially I’m not building a form that directly correlates to the
model in question. For instance a signup form might incorporate some
user properties, and some “throw away” properties (such as those you
might fire at a CC gateway and then forget).

If I created attributes on my user model, I would always need to
supply those properties for validations to pass whereas I only want to
validate these items on this single form in this single location.

What’s the approach to take here?

You can use attr_accessor to create new model attributes that are not
present in the database.

For example, lets say you want to have a field “password” that the user
types in, but this field is not going to be stored in the database.
Instead the table will have a field “encrypted_password” that is created
from the “password” field that the user submits.

class User < ActiveRecord::Base

create a ‘virtual’ attribute

attr_accessor :password

validate its presence only when creating a new record

validates_presence_of :password, :on => :create

set the database field “encrypted_password” based on “password”

before_create :encrypt_password

private

def encrypt_password
#set encrypted PW with industrial strength encryption
self.encrypted_password = self.password.reverse
end

end

Neil M. wrote:

Normally, when using form helpers in Rails, each field directly
correlates to a method on the appropriate object.

However, I have a form (user signup) that needs to include fields that
are not part of the user model itself (for instance, card details) but
need to appear.

How can I build the form so that I can get the necessary fields, and
validate them as I need to (so that it fits with all my other
validations) without dirty-ing my user model?

Essentially I’m not building a form that directly correlates to the
model in question. For instance a signup form might incorporate some
user properties, and some “throw away” properties (such as those you
might fire at a CC gateway and then forget).

If I created attributes on my user model, I would always need to
supply those properties for validations to pass whereas I only want to
validate these items on this single form in this single location.

What’s the approach to take here?

If you can’t use a virtual attribute as Sharagoz described, then you
probably want to put the extra fields in a separate model and use
accepts_nested_attributes_for or something.

Best,
–Â
Marnen Laibow-Koser
http://www.marnen.org
[email protected]