no thanks

Jared Carroll

So I’m learning the latest Rails release by converting an existing app to it. This app used namespaced controllers for its admin section.

New routes features have really cleaned this up.

Before

map.resources :users,
  :controller => 'admin/users',
  :name_prefix => 'admin_',
  :path_prefix => 'admin'

After

map.namespace(:admin) do |admin|
  admin.resources :users
end

Much cleaner.

Then I began to take advantage of Rails 2.0’s smarter #form_for courtesy of simple_helpful in the non-admin portion of the app.

<% form_for @user do |form| %>

<% end %>

If that user object is a #new_record? that #form_for is going to generate the following html:

<form action="/users" method="post" class="new_user" id="new_user">

</form>

If that user object is not a #new_record? that #form_for is going to generate the following html (assuming its id is 1):

<form action="/users/1" method="post" class="edit_user" id="edit_user_1">
  <div style="margin:0;padding:0">
    <input name="_method" type="hidden" value="put" />
  </div>
</form>

Now let’s look at the #new and #edit forms for the admin section of the site.

<% form_for [:admin, @user] do |form| %>

<% end %>

This will generate the same html as above except with ’/admin’ being prefixed onto each action attribute value.

[:admin, @user]

Ooo that is ugly.

Some more examples.

redirect_to [:admin, @user]     # redirect_to admin_user_url

link_to 'show', [:admin, @user] # link_to 'show', admin_user_url

This anonymous Array syntax seems like such a quick hack, like they forgot about namespaced controllers. With all the nice interfaces in Rails, this one really sticks out. I’m willing to bet this becomes deprecated in the near future.

In the meantime I’m going to stick with the much better looking old style.

<% form_for @user, :url => admin_user_url do |form| %>
<% end %>

However, this sucks because I’d really like to take advantage of these smarter #form_for, #redirect_to and #link_to versions but I consider consistency in my code more important. I’d rather see 1 consistent way of using named routes instead of using them solely in the namespaced controller sections of an app in order to avoid this new ugly syntax.

This would probably be a lot cleaner in PHP.