Commit d62568d

mo khan <mo@mokhan.ca>
2015-03-03 03:17:00
display error messages when creating a new item.
1 parent 5030d71
Changed files (3)
app
spec
app/controllers/items_controller.rb
@@ -19,8 +19,13 @@ class ItemsController < ApplicationController
   end
 
   def create
-    current_user.items.create!(secure_params)
-    redirect_to dashboard_path
+    @item = current_user.items.build(secure_params)
+    if @item.save
+      redirect_to dashboard_path
+    else
+      flash[:warning] = @item.errors.full_messages
+      render :new
+    end
   end
 
   def update
app/views/items/_form.html.erb
@@ -1,16 +1,4 @@
 <%= form_for(@item) do |f| %>
-  <% if @item.errors.any? %>
-    <div id="error_explanation">
-      <h2><%= pluralize(@item.errors.count, "error") %> prohibited this item from being saved:</h2>
-
-      <ul>
-        <% @item.errors.full_messages.each do |message| %>
-          <li><%= message %></li>
-        <% end %>
-      </ul>
-    </div>
-  <% end %>
-
   <div class="small-12 columns">
     <%= f.label :name %>
     <%= f.text_field :name %>
spec/controllers/items_controller_spec.rb
@@ -92,6 +92,13 @@ RSpec.describe ItemsController, type: :controller do
 
         expect(response).to redirect_to(dashboard_path)
       end
+
+      context "when some of the fields are invalid" do
+        it "displays the errors" do
+          post :create, item: { name: '' }
+          expect(flash[:warning]).to_not be_empty
+        end
+      end
     end
 
     describe "#update" do