2

我现在的模型是这样的:

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

如您所见,我在模型中设置了一些非数据库字段(use_user_data)的字段...

但是怎么办,如果 :use_user_data 是假的,好的和正确的验证,但是当真时没有验证?

在这里,我想这样做:

  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_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"
4

1 回答 1

0

您可以将条件验证与选项:if:unless. 例子:

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

查看Rails Guide on Validation for 其他 sytntaxes,最后一个可能最适合您的情况:

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
于 2013-01-15T18:30:31.257 回答