仅在virt_attribute为false时验证字段 [英] Validate fields only if virt_attribute is false
问题描述
我有这样的模型:
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)-虚拟属性...
As you can see i set in model some field which is non-db field (use_user_data) - virtual attribute...
但是,如果:use_user_data为假,则正确并正确地进行验证,但如果为true则不进行验证,怎么办?
But how to do, if :use_user_data is false, good and right validate, but when true didn't validate?
我这样尝试:
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
但这对我没有帮助...为什么?
but it doesn't help me... Why?
也是我的表格:
= 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
我收到验证消息...但是,仅当错误时怎么办?为什么我的解决方案不起作用?
i get validation messages... But how to do only if false? And why my solution didn't work?
推荐答案
该表单将"true"或"false"字符串传递给对象,而不是布尔值true
或false
.由于这是一个虚拟属性,因此不会执行任何类型转换.在Ruby中,"true"和"false"都是true
,因此您需要使用某种方法来强制转换值
The form passes "true" or "false" string to the object, not boolean true
or false
. Since it's a virtual attribute, no typecasting performed. In Ruby, both "true" and "false" are true
, so you need to use something to typecast the value
with_options :unless => Proc.new{ |a| a.use_user_data == 'true' } do |order|
order.validates ...
end
或
with_options :unless => :use_user_data? do |order|
order.validates ...
end
def use_user_data?
use_user_data == 'true'
end
这篇关于仅在virt_attribute为false时验证字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!