2

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

validates_presence_of :name, :on => :custom_context

当我保存我使用的数据时

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

这样我的上下文验证规则就被应用了。这工作正常。在我的表单中,名称字段没有用星号标记。我如何告诉我的表单助手我们在:custom_context上下文中并且必须根据需要标记名称字段?

4

2 回答 2

0

我不明白您要做什么,但了解情况。您可以在模型中使用 attribute_accessor -

属性访问器:上下文

在您的视图(.html.erb 文件)中,在您的 <% form_for %> 中执行以下操作

<%= f.hidden_field :context, :value => "custom_context" %>

在你的模型中:

validates_presence_of :name, :if => Proc.new { |variable| variable.context == "custom_context"}

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

于 2013-01-04T10:25:26.833 回答
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
于 2013-01-09T11:58:36.143 回答