我有......
/config/routes.rb:
Testivate::Application.routes.draw do
resources :areas do
resources :heuristics
end
end
/app/models/heuristic.rb:
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:
class Area < ActiveRecord::Base
has_many :heuristics
end
/app/controllers/heuristics_controller.rb:
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:
%h1 New heuristic
= render 'form'
= link_to 'Back', area_heuristics_path(@area)
/app/views/heuristics/_form.html.haml:
= simple_form_for [@area, @heuristic] do |f|
= f.error_notification
= f.input :blueprint_url
= f.button :submit
正如预期的那样,该应用程序不会让我保存一个空的更新:blueprint_url。
但是,错误通知没有出现,我认为这是因为simple_form不知道是否显示@area或@heuristic或其他内容的错误。
如何让它显示我的错误?
rdoc说你可以将选项传递给error_notifications,但它没有说明在这种情况下传递什么选项。
谢谢,
史蒂芬。
答案 0 :(得分:1)
显示错误的方法是在更新失败时呈现模板而不是重定向。重定向时,您将丢失所有错误状态。
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