steven_noble
steven_noble

Reputation: 4213

How to show errors with simple_form with nested models

I have...

/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

As expected, the app won't let me save an update with an empty :blueprint_url.

However, the error notice is not appearing, and I think it's because simple_form doesn't know whether to display errors for @area or @heuristic or something else.

How do I get it to display my errors?

The rdoc says you can pass options to error_notifications, but it doesn't say what option to pass in a situation like this.

http://rubydoc.info/github/plataformatec/simple_form/master/SimpleForm/FormBuilder:error_notification

Thanks,

Steven.

Upvotes: 1

Views: 2504

Answers (1)

Andrew Hubbs
Andrew Hubbs

Reputation: 9436

The way that you display the errors is by rendering a template when the update fails rather than redirecting. When you redirect you are losing all of that error state.

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

Upvotes: 1

Related Questions