我有这样的模型:
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 是假的,好的和正确的验证,但是当真时没有验证?
我这样尝试:
validates :city, :presence => {:message => I18n.t(:city_not_chosen)}, :unless => :use_user_data
所以
with_options :unless => :use_user_data do |order|
order.validates :city, :presence => {:message => I18n.t(:city_not_chosen)}
end
但这对我没有帮助...为什么?
还有我的表格:
= 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"
还有当我写
validates :city, :presence => {:message => I18n.t(:city_not_chosen)}, :if => :use_user_data
我收到验证消息...但是只有在错误的情况下怎么办?为什么我的解决方案不起作用?