【问题标题】:Accessing error messages for nested attribute field访问嵌套属性字段的错误消息
【发布时间】:2012-08-19 07:51:18
【问题描述】:

我有一个使用 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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 error-handling haml simple-form


    【解决方案1】:

    b是form builder的一个实例,持有booking,可以试试:

    # ...
    if b.object.errors[:location]
    # ...
    

    【讨论】:

    • 谢谢!我可以使用 if b.object.errors[:location].empty? 查看是否有任何错误消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多