respond_with在rails3中重定向到指定位置,即使是验证错误也是如此

时间:2011-11-18 22:52:50

标签: ruby-on-rails-3 respond-with

在使用位置响应时,它忽略了验证错误并重定向到指定位置。这是预期的行为吗?

我在responder module检查了它是否检查了模型上是否有任何错误。我检查了模型,它包含@solution对象中的验证错误。我在这里缺少什么?

控制器:

def create
  @problem = Problem.find(params[:problem_id])
  @solution = @problem.solutions.build params[:solution]
  @solution.save
  respond_with(@solution, :location => detail_problem_solution_path(@problem, @solution)
end

模型:

  validates :body, :presence => true, :unless => :reference

引用为true或false false。

2 个答案:

答案 0 :(得分:1)

我今天遇到了这个问题,然后来this Rails issue over at github。由于路由url帮助程序无法为未保存(无效)记录生成有效,因此似乎抛出异常。

关于允许procs作为location参数的参数的github问题的讨论,但它看起来不会很快被添加。

现在我将坚持使用以下解决方案:

def create
  @post = Post.new(params[:post])
  if @post.save
    respond_with(@post, location: edit_post_path(@post))
  else
    respond_with @post
  end
end

答案 1 :(得分:0)

我能解决的唯一方法是:

  def create
    @problem = Problem.find(params[:problem_id])
    @solution = @problem.solutions.build solution_params
    success = @solution.save
    respond_with(@solution) do |format|
      format.html {redirect_to detail_problem_solution_path(@problem, @solution) } if success
    end
  end