Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Why the field with error is not wrapped with "field_with_errors" div when validation fails?

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].

like image 792
Misha Moroshko Avatar asked Jan 02 '26 07:01

Misha Moroshko


1 Answers

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. 
like image 187
Max Williams Avatar answered Jan 04 '26 03:01

Max Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!