views:

154

answers:

5

In Ruby on Rails, is it possible to change a default action for a RESTful resource, so than when someone, for example, goes to /books it gets :new instead of the listing (I don't care if that means not being able to show the listing anymore)?

A: 

Yes. You should be able to replace your index method in your controller...



def index
  @resource = Resource.new
  # have your index template with they proper form
end

The Who
That is not changing the default action, that is making index do something different than listing.
J. Pablo Fernández
Yes but that's very preferable. It's easy to change the action through routes but it would just be a bad idea to do it.
allesklar
+2  A: 

Not sure why would you do such a thing, but just add this

map.connect "/books", :controller => "books", :action => "new", :conditions => { :method => :get}

to your config/routes.rb before the

map.resources :books

and it should work.

Milan Novota
+2  A: 

I'd point out that if you are pointing /books to /books/new, you are going to be confusing anyone who is expecting REST. If you aren't working alone, or if you are and have other come on board later, or if you expect to expose an API to the outside, the REST convention is that /books takes you to a listing, /books/new is where you create a new record.

Kevin Peterson
Actually that is a Rails convention, not a REST one. In fact, any client that takes advantage of that convention to construct Urls is violating the REST self-description constraint by using out of band knowledge.
Darrel Miller
A: 

In the same vein, you can just do

def index
  show
end
Mike H
A: 
def index
  redirect_to new_book_path
end

I think would be the simplest way.

Ryan Bigg