I think this may actually be an object oriented programming question.
Not only am I new to Ruby and Rails, but I’m also coming from a
functional PHP background, so this whole OO approach to web programming
is new to me.
I have a three page registration form and I am trying to determine best
practices for managing the data across forms in a session. I would
like each form to validate before passing the user along to the next
page. The data will be ultimately be distributed across 6 different
tables, so the validation criteria for the registration form is spread
accross the 6 repective model objects.
My thought is to create a non-ActiveRecord model called “Registration”
and have it create the various model objects as instance variables upon
instantiation:
class Registration
def initialize
@member = Member.new
@membership = Membership.new
@donations = Donation.new
…
end
end
and then save this in this object in the session. When I need to
validate the form data, I could do something like this in the
registration controller:
@registration = session[:registration] ||= Registration.new
@member = @registration.member
@member.attributes = params[:member]
redirect_to :action => ‘next_page’ if @member.valid?
That way, I can still use the model (and ActiveRecord) to handle the
nitty gritty of form validation and I only need to manage one object in
the session. Also, if I have a form with data that belongs in three
seperate models how do I validate that data across the various models?
My guess is to add something like this in my registration model:
def valid?
@member.valid?
@membership.valid?
@donation.valid?
@errors =
@member.errors.merge(@membership.errors).merge(@donation.errors)
end
And then this in the view
<%= error_messages_for ‘registration’ %>
Does that look right? I’d like to know if these are common best
practices for handling multipage forms in Rails and if not, how do the
rest of you do it?
Thanks,
Greg