2

My model now is such:

class Order < ActiveRecord::Base
  attr_accessible :**** :phone_number, :receiver, :shipping_id, :street, :totalcost, :user_id, :zip, :use_user_data
  attr_accessor :use_user_data
  validates :city, :presence => {:message =>  I18n.t(:city_not_chosen)}
  validates :zip, :presence => {:message =>  I18n.t(:zip_not_chosen)}
  validates :street, :presence => {:message =>  I18n.t(:street__not_chosen)}
  validates :building, :presence => {:message =>  I18n.t(:building_not_chosen)}
  validates :phone_number, :presence => {:message =>  I18n.t(:phone_number_not_chosen)}
  validates :receiver, :presence => {:message =>  I18n.t(:receiver_not_chosen)}
end

As you can see i set in model some field which is non-db field (use_user_data)...

But how to do, if :use_user_data is false, good and right validate, but when true didn't validate?

Here as i think to do:

  if !:use_user_data
    validates :city, :presence => {:message =>  I18n.t(:city_not_chosen)}
    validates :zip, :presence => {:message =>  I18n.t(:zip_not_chosen)}
    validates :street, :presence => {:message =>  I18n.t(:street__not_chosen)}
    validates :building, :presence => {:message =>  I18n.t(:building_not_chosen)}
    validates :phone_number, :presence => {:message =>  I18n.t(:phone_number_not_chosen)}
    valida

form

= form_for @order do |f|
  %div
    = f.label :use_user_data , "Использовать данные вашего профиля*: "
    = label :use_user_data , "Да"
    = f.radio_button :use_user_data, true, :required => true, :id => "use_user_data", :checked => true
    = label :use_user_data , "Нет"
    = f.radio_button :use_user_data, false, :required => true, :id => "dont_use_user_data"
brabertaser19
  • 5,678
  • 16
  • 78
  • 184

1 Answers1

0

You can use conditional validation with options :if or :unless. Example:

validates :city, :presence => {:message =>  I18n.t(:city_not_chosen)}, :unless => :use_user_data

Look at the Rails Guide on Validation for other sytntaxes, the last one might be the most suitable in your case:

with_options :unless => :use_user_data do |order|
  order.validates :city, :presence => {:message =>  I18n.t(:city_not_chosen)}
  order.validates :zip, :presence => {:message =>  I18n.t(:zip_not_chosen)}
  order.validates :street, :presence => {:message =>  I18n.t(:street__not_chosen)}
  # ...
end
Baldrick
  • 23,882
  • 6
  • 74
  • 79