Answer the question
In order to leave comments, you need to log in
Ruby on Rails 3 validation model
Suppose we have a User model and it has first_name, last_name, email fields. All of them are mandatory. Accordingly, in the model we write
something like this
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :email, :presence => true
and everything would be fine if the form was on one page.
And now the question is how to deal with validation if the form for updating first_name and last_name is on one page and email is on another.
By default, so to speak, on the form where first_name and last_name, if it is submitted, there will be an error that they say email is required and this is true (I need to update email on another page), the same is on the email form where validation will ask for first_name and last_name. I'm interested in how to correctly handle such a situation in Rails 3.
For example, in ASP.NET MVC, I do, as it were, a child ViewModel directly for a specific View, check the fields and then do the property mapping with the parent model. What is the correct way to do this in Rails 3?
Answer the question
In order to leave comments, you need to log in
If I understand your algorithm correctly, then first you create a record with first_name and last_name, and then the email field is updated in the existing record.
Then try
validates :first_name, :presence => true
validates :last_name, :presence => true
validates :email, :presence => true :on => :update
And when adding an email field, load an existing object.
Then on the first form you will have the first two fields checked, you will save the object.
Then, on the second form, you will load the object with the first_name and last_name fields already filled in, and update it. And when updating, validation will work on the email field.
Slightly outdated, but clear on the railscast principle on this subject: railscasts.com/episodes/217-multistep-forms
I did state_machine and validators depending on state
The example on github.com directly shows how to do this
state :first_gear, :second_gear do
validates_presence_of :seatbelt_on
end
using pure Rails on a working system
with_options :if => "cause == 1" do |client|
client.validates :prepay, :cost, :birthday, :phone1, :contract_date, :vin, :adress, :presence => 'true'
client.validates_presence_of :id_series, :id_number, :id_dep
client.validates_format_of :id_series, :id_number , :with => /[\d\s]/
client.validates_presence_of :fio
client.validates :car, :presence => true
end
with_options :if => 'cause == 5' do |client|
client.validates_presence_of :fio, :manager, :trade_in_price, :trade_in_desc
client.validates_associated :used_car
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question