[英]How to get to different and multiple view from controller route Rails 4
I'm moving a Sinatra app I made a while back to Rails 4. In my Sinatra app I had a helper called "logged_in" that returned true if the a user was logged in and returned false otherwise. 我正在将我使用的Sinatra应用程序移回Rails4。在我的Sinatra应用程序中,我有一个名为“ logged_in”的助手,如果用户已登录,则该助手返回true,否则返回false。 Then in my routes I had the following... 然后在我的路线中,我得到了以下...
get '/' do
if logged_in
erb :"admin/a_index"
else
erb :index
end
end
get '/about' do
if logged_in
erb :"admin/a_about"
else
erb :about
end
end
get '/contact' do
if logged_in
erb :"admin/a_contact"
else
erb :contact
end
end
So that if the user was logged in, it would render a different admin view (located in a sub-folder) for that specific static page. 这样,如果用户登录,它将为该特定静态页面呈现一个不同的管理视图(位于子文件夹中)。 If the user wasn't logged in, it would render a default static page. 如果用户未登录,它将呈现默认的静态页面。
How can I implement this in Rails 4? 如何在Rails 4中实现这一点?
Do I have to specify extra admin routes or can I do something like the following... ? 我是否需要指定额外的管理路线,还是可以执行以下操作...?
class PagesController < ApplicationController
def home
if logged_in
render #admin_home
else
render #home
end
end
def about
if logged_in
render #admin_about
else
render #about
end
end
def contact
if logged_in
render #admin_contact
else
render #contact
end
end
end
with just the following routes... 只有以下路线...
Rails.application.routes.draw do
root 'pages#home'
get '/home' => 'pages#home'
get '/about' => 'pages#about'
get '/contact' => 'pages#contact'
get '/signup' => 'users#new'
post '/users' => 'users#create'
get '/login' => 'sessions#new'
post '/login' => 'sessions#create'
get '/logout' => 'sessions#destroy'
end
You can totally just do: 您完全可以做到:
if logged_in?
render 'admin/index'
else
render 'index'
end
But the convention that I've seen in Rails is to have an admin namespace for controllers and views. 但是我在Rails中看到的约定是为控制器和视图提供管理命名空间。 If you're using Devise, it looks like you can write signed in routes like so: 如果您使用的是Devise, 看起来您可以像这样编写签名的路由:
authenticated do
get '/home' => 'admin/pages#home'
end
Which means, of course, that you'd have to specify the same routes for non-signed in users. 当然,这意味着您必须为未登录的用户指定相同的路由。 But then you'd have a separate controller (AdminPagesController in contorllers/admin) and action for admin in case you need to load different data. 但是,如果您需要加载其他数据,那么您将拥有一个单独的控制器(contorllers / admin中为AdminPagesController)和admin的操作。 Views would then go in views/admin/. 然后,视图将进入views / admin /。
Answer is no. 答案是否定的。 Render only renders a specific page, it doesn't call any new routes. 渲染仅渲染特定页面,不调用任何新路线。 That is what redirect_to
does: it calls a whole new route. 那就是redirect_to
所做的:它调用了一条全新的路由。 You can call render
for any view in your application, just as long as you have the right instance variables to make it display properly. 您可以为应用程序中的任何视图调用render
,只要您具有正确的实例变量以使其正确显示即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.