我很难理解如何让Rails显示在呈现XML模板时验证失败的子资源的显式错误消息.假设我有以下课程:

class School < ActiveRecord::Base
    has_many :students
    validates_associated :students

    def self.add_student(bad_email)
      s = Student.new(bad_email)
      students << s
    end
end

class Student < ActiveRecord::Base
    belongs_to :school
    validates_format_of :email,
                  :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
                  :message => "You must supply a valid email"
end

现在,在控制器中,让我们假设我们想要构建一个简单的API,允许我们添加一个新的学校,其中有一个学生(我说,这是一个很糟糕的例子,但在问题中起到了作用)

class SchoolsController < ApplicationController
    def create
      @school = School.new
      @school.add_student(params[:bad_email])
      respond_to do |format|
          if @school.save
          # some code
          else
            format.xml  { render :xml => @school.errors, :status => :unprocessable_entity }
          end
      end
    end
end

现在验证工作正常了,因为邮箱与学生类中validates_format_方法中设置的正则表达式不匹配,所以一切都会消失.然而,我得到的结果如下:

<?xml version="1.0" encoding="UTF-8"?>
<errors>
  <error>Students is invalid</error>
</errors>

我希望上面用validates_format_设置的更有意义的错误消息显示出来.意思是,我想说:

 <error>You must supply a valid email</error>

我做了什么错事让它不出现?

推荐答案

School模型中添加验证块以合并错误:

class School < ActiveRecord::Base
  has_many :students

  validate do |school|
    school.students.each do |student|
      next if student.valid?
      student.errors.full_messages.each do |msg|
        # you can customize the error message here:
        errors.add_to_base("Student Error: #{msg}")
      end
    end
  end

end

现在@school.errors将包含正确的错误:

format.xml  { render :xml => @school.errors, :status => :unprocessable_entity }

Note:

将新学生添加到学校不需要单独的方法,请使用以下语法:

school.students.build(:email => email)

Rails 3.0的更新+

errors.add_to_base已从Rails 3.0及以上版本中掉落,应更换为:

errors[:base] << "Student Error: #{msg}"

Ruby-on-rails相关问答推荐

如何测试自定义路由?

如何将Form_With用于多个没有控制器的型号

如何在Rails中创建没有字符串的查询

Rails6.1|有没有一种方法可以判断哪些关联已经加入到一个范围中?

Rails ActiveRecord::LogSubscriber 不输出详细查询日志(log)

Ruby on Rails 身份验证:设计注册不起作用

错误原始错误:未安装 ImageMagick/GraphicsMagick

GroupingError:错误:列必须出现在 GROUP BY 子句中或在聚合函数中使用

Rails:序列化数据库中的对象?

Rails - 如何使用子对象的嵌套属性和强参数填充父对象ID?

基于 2 列定义唯一主键

Rails:文件路径

在 rake 任务期间关闭观察者的简单方法?

使用 AJAX 向 Rails 发送 Authenticity Token 的正确方法

如何一次显示一条 Ruby on Rails 表单验证错误消息?

如何翻译 ActiveRecord 模型类名称?

Rails 3 设计,current_user 在模型中不可访问?

Rails:弃用警告:您没有设置 config.secret_key_base

ruby on rails 如何处理 NaN

Rails:您已经激活了 rake 10.3.1,但您的 Gemfile 需要 rake 10.2.2 (Gem::LoadError)