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