Rails具有关联和嵌套属性的自定义验证

时间:2016-06-29 18:26:31

标签: ruby-on-rails ruby

TaskCategory有很多Tasks。当用户创建任务时,他以相同的形式创建与任务关联的任务类别:

<%= form_for @task, remote: true, html: { class: 'form' } do |f| %>
    ...
    <%= f.fields_for :task_category, f.object.build_task_category do |task_category_builder| %>
      <%= validate_select_field task_category_builder, :task_category, nil, {required:true} do %>
        <%= task_category_builder.select :id, TaskCategory.all.collect {|task_category| [ task_category.name, task_category.id ] }, {include_blank: true}, { class: "form-control" } %>
      <% end %>
    <% end %>
<% end %>

validate_select_field帮助器,为表单控件配置样式,但也检查对象是否包含任何错误:

def validate_select_field(form, attr, label, options={})
  ...
  container_class += " has-error has-feedback" if form.object && form.object.errors[attr].present?
  ...
end

因此,我需要专门化错误对象以匹配属性的名称。在TaskCategory中,我添加了自定义错误:

class Task < ActiveRecord::Base
  belongs_to :task_category

  accepts_nested_attributes_for :task_category

  validates :task_category, presence: true
end

class TaskCategory < ActiveRecord::Base
  has_many :tasks

  validate name_present

  private

  def name_present
    unless self.name.present?
      errors["task[task_category_attributes][id]"] << "must be present"
    end
  end 
end

但是,当我添加name_present方法时,上面的f.fields_for :task_category调用失败,并出现以下异常:

NameError - uninitialized constant Task::TaskCategory:

为什么会发生此错误,如何自定义关联错误?

0 个答案:

没有答案