7

我有一个使用simple_form gem创建的表单,该表单使用嵌套属性填充2个模型。我想检查是否有任何错误,并显示一个新的块。但是,我不确定如何正确访问Booking型号的location属性的错误消息。访问嵌套属性字段的错误消息

class Booking < ActiveRecord::Base 
    belongs_to :customer 

    attr_accessible :date_wanted, :location 
end 

class Customer < ActiveRecord::Base 
    has_many :bookings 
    accepts_nested_attributes_for :bookings 

    attr_accessible :name, :phone, :bookings_attributes 

    validates_presence_of :name, :phone 
end 

表单视图:

simple_form_for @customer, {:html => { :class => "form-horizontal" }} do |f| 
    = f.input :name 
    = f.input :phone 
    = f.simple_fields_for :bookings do |b| 
    = b.input :date 
    = b.input :location 
    - if @customer.errors[:appointments_attributes][:location] 
     # insert code if any validation errors for the date field were found 
    = f.button :submit 

回答

7

b是表单生成的一个实例,拿着booking,所以你可以尝试:

​​
+1

谢谢!我可以通过使用'b.object.errors [:location] .empty?'来查看是否有任何错误消息。 – dspencer