仅当virt_attribute为false时才验证字段

时间:2013-01-16 12:08:03

标签: ruby-on-rails ruby-on-rails-3 validation model

我有这样的模特:

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时没有验证?

我试试:

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

我收到验证消息......但是只有在假的时候怎么做?为什么我的解决方案不起作用?

2 个答案:

答案 0 :(得分:2)

表单将“true”或“false”字符串传递给对象,而不是布尔truefalse。由于它是虚拟属性,因此不执行类型转换。在Ruby中,“true”和“false”都是true,因此您需要使用某些东西来对类值进行类型转换

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

答案 1 :(得分:0)

您需要将:if:unless条件置于lambda或Proc

validates ..., :if => Proc.new { |a| a.use_user_data === false }

这会导致在验证期间执行上述:use_user_data行之前不会对validates进行评估(Proc作为值传递给{{1}或者:if选项由Rails评估:unless将接收当前模型属性作为参数,允许您检查这些属性(在这种情况下,Proc:use_user_data