2012-11-03 137 views
0

我在我的Rails项目中有usersprojects脚手架。我也有一个admin控制器和视图,只有管理员用户可以访问。我希望usersprojects模型的indexcreate控制器操作仅可通过admin视图访问(使用render :partial > 'index'),但我不想让访问者能够输入http://railsapp.host/users并获得部分呈现。我如何实现这一目标?Rails - 只允许访问控制器动作到服务器端

为了澄清,我的问题不是关于用户角色。我使用所有require_admin助手进行authlogic,但我甚至不希望管理员用户能够直接从浏览器访问usersindex路由。实际上我想给index控制器动作仅限制于admin#index这样的视图代码:

<%= render '/users/index' %> 
+0

最简单的方法在这里描述:http://guides.rubyonrails.org/action_controller_overview.html#http-authentications。 – jdoe

回答

0

好的过滤器,我应该说我是一个相对的小白到轨道。我想到了它。我以为

<%= render '/users/index' %> 

实际上通过​​代码。我只是想知道,只是在没有通过控制器操作的情况下调用部分视图。所以我只是已将此添加到users控制器

def index 
    redirect_to :controller=>'admin', :action=>'index' 
end 

这似乎达到我所寻找的目标。

感谢您的帮助。

0

如果您使用不同的用户角色,你可以检查管理员用户的角色,然后渲染部分,例如:

<% if user.isAdmin? %> 
    <%= render 'index' %> 
<% end %> 
+0

感谢您的回复。我的问题不清楚 - 我只是编辑它。请参阅编辑。 – pvenky

+0

我不明白你想做什么,但如果你想设置用户的能力,你可以尝试[Can Can](https://github.com/ryanb/cancan)gem。 – Thanh

+0

Thanh,我有一个'users#index'控制器动作来呈现部分。但是这部分内容嵌入在'admin#index'视图中。我不想让任何人能够输入“https:// localhost/users”并获得部分内容。实际上,我需要能够在我的用户控制器中辨别请求是来自直接输入到浏览器中的Web地址还是来自“admin#index”操作呈现期间。 – pvenky

1

的最佳轨道的方法是定义应用控制器

class UsersController < ApplicationController 
    before_filter :check_isadmin?, :only => [:create, :index] 
end 
class ProjectsController < ApplicationController 
    before_filter :check_isadmin?, :only => [:create, :index] 
end 
class ApplicationControlloller < ApplicationController 
    def check_isadmin? 
     current_user.admin? 
    end 
end 
+0

感谢您的回复。我的问题不清楚 - 我只是编辑它。请参阅编辑。 – pvenky

0

对Aayush Khandelwal的补充对我有帮助before_filter在Rails 5上折旧。改用before_action。

class UsersController < ApplicationController 
    before_action :check_isadmin?, :only => [:create, :index] 
end 

和in:check_isadmin?如果为false,则重定向到其他页面。

def check_isadmin? 
    if current_user == nil || !current_user.admin? 
    redirect_to root_path 
    end 
end 
相关问题