Rails使用上下文验证形成输入

时间:2013-01-04 10:14:13

标签: ruby-on-rails validation

在我的应用中,我有一个像这样的验证规则

validates_presence_of :name, :on => :custom_context

当我保存数据时,我使用

@obj.save(:context => :custom_context)

以便应用我的上下文验证规则。这很好用。在我的表单中,名称字段未标有星号。如何告诉我的表单助手我们在:custom_context上下文中,并且名称字段必须标记为必需?

2 个答案:

答案 0 :(得分:0)

我不明白你想要做什么但是理解了这个场景。 您可以在模型中使用attribute_accessor说 -

  

attribute_accessor:context

在您的视图(.html.erb文件)中,在<%form_for%>

中执行以下操作
<%= f.hidden_field :context, :value => "custom_context" %>

在你的模特中:

  

validates_presence_of:name,:if =&gt; Proc.new {|变量|   variable.context ==&#34; custom_context&#34;}

我认为这应该有所帮助:D

答案 1 :(得分:0)

好吧,我想没有完美的方法可以做到这一点。最终我做了类似的事情:

<%= f.input :name, :required => required_in_context?(:name, :custom_context) %>

我写了一个辅助方法:

def required_in_context? field, context
  required = false
  MyClass.validators.each do |v|
    required = true if v.kind == :presence && v.attributes.include?(field) && v.options == {:on => context}
  end
  required
end