【问题标题】:Rails 3: Why the field with error is not wrapped with "field_with_errors" div when validation fails?Rails 3:当验证失败时,为什么有错误的字段没有用“field_with_errors”div 包裹?
【发布时间】:2011-05-28 14:07:37
【问题描述】:

我的Product类有price字段,在数据库的Products表中有合适的列,还有new_shop辅助字段(定义为attr_accessor,没有合适的列在数据库中的Products 表中)。

price 验证失败时,输入字段用field_with_errors div 包裹,但new_shop 验证失败时,它不被field_with_errors div 包裹。为什么?

这是为这些输入字段生成的 HTML:

<input type="text" name="product[price]" id="product_price">
<input type="text" value="" name="product[new_shop]" id="product_new_shop">

更多信息:

class Product < ActiveRecord::Base
  attr_accessor :new_shop 
  accepts_nested_attributes_for :shop
  validates_presence_of :price
  ...
end

class Shop < ActiveRecord::Base
  validates_presence_of :name
  ...
end

提交表单时,new_shop 值将传递给产品的shop_attributes[:name]

【问题讨论】:

  • 请附上验证码

标签: ruby-on-rails validation ruby-on-rails-3 field-with-errors


【解决方案1】:

所以实际上验证失败的是 :name 属性?这就是为什么 new_shop 没有得到 fieldWithErrors div 的原因:这会查看 @product.errors 以逐个字段地确定它是否有错误。即

#comes to do the :new_shop field
#looks to see if @product.errors.on(:new_shop) is not blank
#if it isn't blank, wraps the error div round it. 

【讨论】:

  • 非常感谢!一个小问题:on 方法是做什么的?我没有找到关于它的文档。请给我介绍一下好吗?
猜你喜欢
  • 2016-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多