views:

250

answers:

2

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?

+3  A: 

I'm not sure what you mean by "dirty-ing" your user model, but you can do this using the attr_accessor method. This will allow you to create an attribute for the model that can be used for validations:

class Widget < ActiveRecord::Base
  attr_accessor :confirmation_email
  validates_length_of :confirmation_email, :within => 1..10
end

To only run the validation at certain times, you could use an :if condition:

validates_length_of :confirmation_email, :within => 1..10, :if => Proc.new { |widget| widget.creation_step > 2 }

You can also use a class method, like: :if => :payment_complete. With these you should be able to achieve the functionality you want. As far as I know there isn't any more concise way.

Benjamin Manns
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.
Neil Middleton
I've added information about the :if condition, which might be what you are looking for.
Benjamin Manns
A: 

Yehuda Katz has a great explaination of how you can use ActiveModel to make an arbitrary class compatible with Rails' form helpers. That only works if you're on Rails 3, though.

If you're not living on the bleeding edge, watch Railscasts episode 193, "Tableless Model", which describes how you can create a class that quacks enough like ActiveRecord::Base that it works with form_for.

James A. Rosen