【问题标题】:Show and hide based on user role in rails根据 Rails 中的用户角色显示和隐藏
【发布时间】:2012-12-14 03:06:40
【问题描述】:

我的home.html.erb 文件中有以下代码;

<!-- if seeker is logged in show button "Grab it" -->
<% if user_signed_in? %>
<div class="grabit alignright">
<small>want to work on this?</small>
<!-- if seeker is not logged in, show him the output text of "Sign in to work on this job" -->
<% else %>
<small>are you a guru? want to work on this? Sign up.</small>
<% end %>
</div>

现在您可以看到,我正在尝试让 Seeker 作为用户角色。根据具有该类型角色的该类型用户是否已登录,将显示不同的内容。

我已经安装了 Devise + CanCan。现在对此非常陌生,我已经查看了所有内容以了解如何执行此操作。我将拥有具有普通用户角色的“用户”和具有搜索者角色的“搜索者”。使用上面的代码只显示用户何时登录,而不是搜索者。

seekers_signed_in这么简单吗?我应该使用什么?与user_signed_in比较?我已经为用户、搜索者和管理员生成了设计视图。管理员将能够为用户和搜索者删除、更新等。用户发布项目,搜索者抓取它们。

谁能帮忙?

【问题讨论】:

    标签: ruby-on-rails controller roles cancan


    【解决方案1】:

    您不必创建用户和搜索者(两个设计模型),而是可以只创建一个通用模型并将其命名为用户,然后根据需要添加任意数量的角色。

    我推荐使用这个gem 来轻松配置角色,

    然后在您的home.html.erb 中,您只需执行以下操作:

    <!-- if seeker is logged in show button "Grab it" -->
    <% if user_signed_in? && current_user.is_seeker? %>
    <div class="grabit alignright">
    <small>want to work on this?</small>
    <!-- if seeker is not logged in, show him the output text of "Sign in to work on this job" -->
    <% else if !user_signed_in?%>
    <small>are you a guru? want to work on this? Sign up.</small>
    <% else%>
    <small>You are not a seeker, you need to be a seeker!</small>
    <% end %>
    </div>
    

    CanCan 用于控制器级别,因此上述方法对于您的情况来说既简单又直接。

    我希望这会有所帮助。

    【讨论】:

    • 嗨,这也适用于寻求者和用户有不同观点的方法吗?而不是一个简单的 home.html.erb 页面? -谢谢!
    • 因为可以访问user_signed_in? && current_user 从任何视图,您都可以在任何视图中检查 current_user 是否是搜索者.. 记住它的一个用户模型,在您的所有应用程序中使用,您是否检查了简单角色 gem?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2011-02-25
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    相关资源
    最近更新 更多