You want a RESTful Rails app with a backend administration? The worst thing to do in my opinion is to use the same controllers for the public and the admin side. At first, it might look wise to do this. I mean, if you have a “books” resource, it would be logical that all methods related to books go in the same controller, right? Well, logical or not… I suggest you never do this because your application will become a real mess in no time. Personally, I did it once and will never get caught again!
Exemple of a mess in a controller :
def index if administrator? @books = Book.all else @books = Book.published end end
Example of a mess in a view :
<%if administrator?%> <%=render partial: "admin_index"%> <%else%>
Published booksbla bla bla <%end%>
If you go that route, be prepared to make your fingers bleed because you will write tons of confusing and ugly “if” statements everywhere. Most of the time anyway, what you need to do with the resources is completely different depending if you’re on the admin or public side, so you’re better to separate them.
Step #1 : Generating the controllers
To generate a public controller, you do like you always do : ./script/generate controller books
To generate its admin counterpart, you simply do this : ./script/generate controller admin/books
Rails will generate the controller in controllers/admin/books_controller.rb and a folder for the views in views/admin/books
Step #2 : Configuring the routes
One route for the public side :
map.resources :books, :only => [:index, :show]
One route for the admin side
map.namespace :admin do |admin| admin.resources :books admin.resources :some_other_resource end
Now your namespaced controller has its own named urls as well : admin_books_url, edit_admin_book_url and so on…
Step #3 : Get the “form_for” url right
<%form_for [:admin, @book] do |f|%> <%=f.text_field :title%> <%=f.submit "save"%> <%end%>
That way Rails will correctly call the update/create method in controllers/admin/books_controller.rb instead of the one in controllers/books_controller.rb
A final note
The controllers and the views are best kept separated but NOT the model which should always remain unique in your app.