views:

81

answers:

2

Users can view a specific entry in my webapp with a URL. /entry/8, for example. If an entry doesn't exist, "Entry not found" gets appended to @messages and I render an error page.

I'd like to show some arbitrary query instead of a blank page, but I can't figure out a good way to keep the error message around to be displayed. There are other actions that need to take place in the arbitrary query's controller, so I can't just duplicate the query and render :posts.

Some example code:

module MyApp::Controllers
  class ComplexQuery < R '/query'
    def get
      @entries = Entries.all(:conditions => someComplexConditions)
      until @entries.complexEnough? then @entries.makeMoreComplex! end
    end
  end

  class SingleEntry < R '/entry/(\d+)'
    def get(id)
      @entries = Entries.find_all_by_id(id)
      unless @entries.nil?
        render :posts
      else
        @messages = ["That entry does not exist."]
        render :blank  # I want to run Controllers::ComplexQuery, instead of rendering a blank page.
      end
    end
  end
end
A: 

Try this:

@entry = Entry.find_by_id(params[:id]) # returns nil when not found
if @entry.nil?
  flash[:notice] = "Entry not found"
  render :action => "recent" 
end
KandadaBoggu
I don't want to duplicate the query. For recent posts it's a simple thing, but duplicating all the handling to repeat a potentially complex user-input query is a lot of work for every controller that could potentially have a validation fail.
echoback
The query conditions wouldn't be user-input, but you get the idea, I hope.
echoback
+3  A: 

Something like this?

def get(id)
  @entries = Entries.find_all_by_id(id)
  unless @entries.nil?
    render :posts
  else
    r *MyApp.get(:ComplexQuery)
  end
end

See Camping.method_missing.

But I would also recommend moving ComplexQuery into a helper method:

module MyApp::Helpers
  def complex_query(conditions); end
end

Then you can complex_query(something) in both SingleEntry and ComplexQuery.

Magnus Holm