I start out with this:
MODEL
class Item < ActiveRecord::Base validates_presence_of :title, :description, :link end
CONTROLLER
class ItemController < ApplicationController
# other actions here...
def create @item = Item.new(params[:item]) if @item.save flash[:notice] = 'Item was successfully created.' redirect_to :action => 'list' else render :action => 'new' end end end
FORM
<%= error_messages_for 'item' %>
<!--[form:item]--> <p><label for="item_title">Title</label><br/> <%= text_field 'item', 'title' %></p>
<p><label for="item_link">Link</label><br/> <%= text_field 'item', 'link' %></p>
<p><label for="item_description">Description</label><br/> <%= text_area 'item', 'description' %></p>
<!--[eoform:item]-->
So, if any of title/descripton/link are missing when I create an Item, the new page is re-rendered with a nice set of error messages.
However, I next create a list consisting of a feed (parent) with multiple children (items) using acts_as_list. The model code for Item now looks like this:
MODEL
class Item < ActiveRecord::Base belongs_to :feed acts_as_list :scope => :feed_id validates_presence_of :title, :description, :link end
For the controller, I tried several things but nothing quite works.
CONTROLLER SCENARIO #1
def create feed = Feed.find(session[:current_feed_id]) if feed.items.create(params[:item]) flash[:notice] = 'Item was successfully created.' redirect_to :action => 'list' else render :action => 'new' end
This is fine if everything validates. The item is created successfully, all the acts_as_list columns are in synch.
But (as I discovered) create essentially returns true whether validation fails or not. So the if test is useless. This can also be verified by using the bang version of create (create!). In that case, an exception is thrown and the exception messages indeed indicate all the validation violations.
Given this, I next tried the following:
CONTROLLER SCENARIO #2 (create!)
def create feed = Feed.find(session[:current_feed_id]) begin feed.items.create!(params[:item]) flash[:notice] = 'Item was successfully created.' redirect_to :action => 'list' rescue render :action => 'new' end
This code catches validation exceptions correctly, The 'new' page was, in fact, be re-rendered but alas, no error messages.
I didn't look at the validation code before doing this (probably should have). But I was hoping that the error message packaging for the forms (<%= error_messages_for 'item' %>) was synched with exceptions since the messages were the same.
I could, I suppose, catch the errors in 'rescue' and put out my own error messages but I can't help but think that I'm just missing something here since this must be a fairly common occurrence.
Any ideas?