Different layouts and routes on single views for a resource
I'm new to rails and have a question regarding layouts and routing in a CMS. I haven't come across an answer on this particular issue after searching the web so I hope someone here could help me.
I'm building a CMS and have to layouts, application.html.erb (default) which is the front public page and admin.html.erb which is available after logging in.
I have resource called Post. Is it possible that only the show view uses the default layout while the rest of the views uses the admin layout?
In other words I want urls to single posts to be like "myAppDomain/posts/1" and use the default layout
while administrative views should have /admin as a prefix and use the admin layout, like "myAppDomain/admin/posts", "myAppDomain/admin/posts/1/edit"Now I've set up a route that "adds" the /admin to the posts urls
scope "/admin" do
resources :posts
end
And in the PostsController I specify to use the admin layout
class PostsController < ApplicationController
before_filter :authorize , :except => [:show]
layout 'admin'
...
So now people can read posts without logging in, but the links to the single post view on my welcome page is rendered "myAppDomain/admin/posts/1" and it uses the admin layout
<%= link_to post.title, post %>
Is there a way to use di开发者_如何学编程fferent layouts and routes on single views for a resource or should I go for a different approach?
Just specify the layout in the action
def show
render :layout => 'application'
end
You can do a before_action
private
def layout_set
if current_user.admin?
layout 'admin'
else
layout 'default'
end
end
At the top of the controller:
before_action :layout_set
Now you can forget about adding the layout. You can take it a step further and put the before action in your application controller and you can add that functionality in all your controllers by just adding the same before_action. You save a lot of extra code this way.
精彩评论