如果条件在rails 3.2和mongoid + simple_form上,则为validates_presence_of

hyp*_*jas 4 validation ruby-on-rails ruby-on-rails-3

我想要验证这两个属性的存在:shipping_cost以及:shipping_cost_anywhere属性:shipping是否相等true.而如果

我的模型中有这个,但对我来说效果不好:

validates_presence_of :shipping_cost, :shipping_cost_anywhere, :allow_blank => "true" if :shipping == "true"
Run Code Online (Sandbox Code Playgroud)

这是我的:运输属性:

field :shipping, :type => Boolean, :default => "false"
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

谢谢!

编辑.

我正在使用mongoid和simple_form宝石

den*_*nis 12

validates_presence_of :shipping_costs_anywhere, :if => :should_be_filled_in?

def should_be_filled_in?
  shipping_costs_anywhere == "value"
end
Run Code Online (Sandbox Code Playgroud)

在语句中调用时,该方法将返回true或false.无需在shipping_costs_anywhere前放置冒号.

  • 条件验证需要方法的符号 (3认同)

hyp*_*jas 5

我对这个问题的解决方法是下一个代码:

validates :shipping_cost, :shipping_cost_anywhere, :presence => true, :if => :shipping?
Run Code Online (Sandbox Code Playgroud)

感谢大家的帮助,但任何答案都对我有用.谢谢!