我的模特现在是这样的:
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
如你所见,我在模型中设置了一些非db字段的字段(use_user_data)......
但该如何做,if:use_user_data为false,good和right验证,但是当true为true时没有验证?
我认为这样做:
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"
答案 0 :(得分:0)
您可以对选项:if
或:unless
使用条件验证。示例:
validates :city, :presence => {:message => I18n.t(:city_not_chosen)}, :unless => :use_user_data
查看其他sytntax的Rails Guide on Validation,最后一个可能是你最合适的:
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