繁体   English   中英

理解Rails中的`respond_with`

[英]Understanding `respond_with` in Rails

我有一个带有before_createbefore_update回调的模型可以return false 当回调失败时(如预期的那样),不会保存模型,但是我的控制器将重定向到未创建的模型上的索引路径(与呈现新模板相对)。 我的代码是:

class Person
  before_create :reversify
  before_update :reversify

  def reversify
    return false if self.name.blank?
    self.name = self.name.reverse
  end
end

class PeopleController < ApplicationController

  respond_to :html

  def new
    @person = Person.new
    respond_with(@person)
  end

  def create
    @person = Person.create(params[:person])
    respond_with(@person)
  end

end

respond_with使用@person.errors的存在/不存在来确定适当的RESTful响应。

我要推论,因为您依靠使用失败的回调来防止保存无效对象,所以ActiveRecord不会填充@person.errors ,这将导致ActionController::Responder确定保存成功。

我建议重新编写Person类以使用验证:

class Person
  before_save :reversify

  validates :name, :presence => true

  def reversify     
    self.name.reverse!
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM