[Rails 3] Trouble with named routes and form_for

Hi guys,

I’m having trouble getting named routes and form_for to play nicely in quite the way I would expect. Here’s a quick summary of what I’ve got going on:

Named route:

resources :thread, :class_name => "forum_thread"

Controller name:

forum_thread_controller

Model object:

forum_thread

In both my new and edit actions I’m setting up an @thread variable:

@thread = ForumThread.new

1.) My first attempt at writing the form_for looked something like this:

<%= form_for @thread do |f| %>

<% end>

This didn’t work because @thread tries to use a path involving the string “forum_thread”, which doesn’t have a matching route and which I don’t want.

2.) So that’s fine, I figured I’d just use named routes. So I tried this:

<%= form_for @thread, :as => :thread, :url => thread_path(@thread) do |f| %>

<% end >

This works for edit actions, but not for new actions. On new I get the following error:

No route matches {:action=>“destroy”, :controller=>“forum_thread”, :id=>#<ForumThread id: nil, …>}

3.) So then I tried:

<%= form_for @thread, :as => :thread, :url => threads_path(@thread) do |f| %>

<% end >

This doesn’t work for edit, and sorta works for new except it outputs the following HTML, which makes the respond_to block unhappy:

....

4.) So then I tried:

<%= form_for @thread, :as => :thread, :url => threads_path do |f| %>

<% end >

Now everything works for new, but not for edit! (Because the ID of the element being edited isn’t emitted as part of the action):

So:

  1. Is there some way to use a named route that uses a custom class name and still be able to reuse my form partial for both new and edit actions? Or am I stuck writing two forms?

  2. Is the error I received in #2 a bug in Rails 3 or expected behavior?

  3. Is the erroneous output in #3 a bug in Rails 3 or expected behavior?

My sincere thanks in advance for your help!

-Jury

I’ve also tried

<%= form_for @thread, :as => :thread %>

and this results in the error:

undefined method `forum_threads_path’ for #<#Class:0x00000103a45098:0x000001039575a0>

That would seem to be a bug to me. Shouldn’t form_for be using :as => :thread to name that route appropriately?

-M