Reputation: 2253
I am building an admin interface for a website. I have certain controllers that have admin functions/views that also have user facing views. For example, when a user goes to /blog, it should show the title, date, first paragraph, etc. of each blog post with links to read the whole post. If an admin goes to admin/posts they would see a list of just the blog post titles, how many comments, edit/delete links, link to create a post, etc.
How would I accomplish this? My (simplified) routes files is this:
namespace :admin do
resources :posts
end
Do I need to have separate controllers?
Upvotes: 0
Views: 680
Reputation: 17631
Usually when using namespaces
you want your code to be namespaced as well. I would go for 2 different controllers serving 2 different views.
app/controllers/posts_controller.rb
app/controllers/backend/posts_controller.rb
or
app/controllers/posts_controller.rb
app/controllers/admin_area/posts_controller.rb
You get the idea. I would do the same thing with the views.
You controllers would look like this:
class PostsController < ApplicationController
end
class Backend::PostsController < BackendController
end
class BackendController < ApplicationController
end
Upvotes: 2
Reputation: 2519
There are quite a few ways you could approach this, I can't really think of one being "right" over the other. For simplicity's sake, I'll offer one quick solution, though, admittedly, it's a shortcut.
Presumably, you have a logged in user going to this /admin route, and the current_user would be authorized as an admin, so you can use that to your advantage in your show method.
if current_user.admin?
render 'admin_show'
else
render 'show'
Your views, of course, would render the different implementations.
If you are going to have a number of differences in what the methods do, though, it may be worth creating a new admin_posts_controller. But if there are only a couple differences, then that could be good enough.
Meh, hope that helps.
Upvotes: 0