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 different layouts and routes on single views for a resource or should I go for a different approach?
A layout defines the structure for a user interface in your app, such as in an activity. All elements in the layout are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see and interact with.
Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. A single call to resources can declare all of the necessary routes for your index , show , new , edit , create , update , and destroy actions.
Rails RESTful Design which creates seven routes all mapping to the user controller. Rails also allows you to define multiple resources in one line.
In Rails, layouts are pieces that fit together (for example header, footer, menus, etc) to make a complete view. An application may have as many layouts as you want. Rails use convention over configuration to automatically pair up layouts with respective controllers having same name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With