首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用嵌套模型显示simple_form错误

如何用嵌套模型显示simple_form错误
EN

Stack Overflow用户
提问于 2012-11-21 00:01:29
回答 1查看 2.5K关注 0票数 1

我有。

/config/routes.rb:

代码语言:javascript
复制
Testivate::Application.routes.draw do
  resources :areas do
    resources :heuristics    
  end
end

/app/models/heuristic.rb:

代码语言:javascript
复制
class Heuristic < ActiveRecord::Base
  attr_accessible :area_id, :blueprint_url
  belongs_to :area
  validates :blueprint_url, :presence => {:message => "Please type the blueprint's internet address"}
end

/app/models/area.rb:

代码语言:javascript
复制
class Area < ActiveRecord::Base
  has_many :heuristics
end

/app/controllers/heuristics_controller.rb:

代码语言:javascript
复制
class HeuristicsController < ApplicationController
  def edit
    @area = Area.find(params[:area_id])
    @heuristic = Heuristic.find(params[:id])
  end
 def update
  @heuristic = Heuristic.find(params[:id])
  @area = Area.find(params[:area_id])
  respond_to do |format|
    if @heuristic.update_attributes(params[:heuristic])
      format.html { redirect_to areas_path, notice: 'Heuristic was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { redirect_to edit_area_heuristic_path(@area, @heuristic) }
      format.json { render json: @heuristic.errors, status: :unprocessable_entity }
    end
  end
 end
end

/app/views/heuristics/new.html.haml:

代码语言:javascript
复制
%h1 New heuristic
= render 'form'
= link_to 'Back', area_heuristics_path(@area)

/app/views/heuristics/_form.html.haml:

代码语言:javascript
复制
= simple_form_for [@area, @heuristic] do |f|
  = f.error_notification
  = f.input :blueprint_url
  = f.button :submit

正如预期的那样,这个应用程序不会让我用一个空的:blueprint_url保存更新。

但是,错误通知并没有出现,我认为这是因为simple_form不知道是显示@area或@启发式的错误还是其他什么。

我如何让它显示我的错误?

rdoc说,您可以将选项传递给error_notifications,但它没有说明在这种情况下应该传递什么选项。

notification

谢谢,

史蒂文。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-21 01:56:49

显示错误的方式是在更新失败时呈现模板,而不是重定向。当您重定向时,您正在丢失所有的错误状态。

代码语言:javascript
复制
def update
  @heuristic = Heuristic.find(params[:id])
  @area = Area.find(params[:area_id])
  respond_to do |format|
    if @heuristic.update_attributes(params[:heuristic])
      format.html { redirect_to areas_path, notice: 'Heuristic was successfully updated.' }
      format.json { head :no_content }
    else
      format.html { render "edit" } # This is the thing that will get your error state
      format.json { render json: @heuristic.errors, status: :unprocessable_entity }
    end
  end
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13484314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档