3

My Product class has price field, which has an appropriate column in Products table in the database, and new_shop helper field (which is defined as attr_accessor, and does not has an appropriate column in Products table in the database).

When validation on price fails, the input field is wrapped with field_with_errors div, but when the validation on new_shop fails, it is not wrapped with field_with_errors div. Why ?

Here is the generated HTML for these input fields:

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

Some more info:

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

When the form is submitted, the new_shop value is passed to product's shop_attributes[:name].

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

3

So it's the :name attribute that actually fails validation? That is why new_shop doesn't get the fieldWithErrors div then: this looks at @product.errors to decide on a field by field basis whether it has errors. ie

#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. 
Max Williams
  • 32,435
  • 31
  • 130
  • 197
  • Thanks a lot! One little question: what does the `on` method do ? I didn't find a documentation on it. Could you refer me please ? – Misha Moroshko Dec 21 '10 at 12:54