Ruby on Rails(三)隐藏部分视图 [英] Ruby on Rails (3) hiding parts of the view

查看:41
本文介绍了Ruby on Rails(三)隐藏部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 Ruby on Rails 3 网络应用程序.

I am working on a Ruby on Rails 3 web application.

我有一个名为 User 的表,其中有一个名为 role 的表.我正在寻找对视图的这些部分具有错误"角色的用户隐藏部分视图的最佳方法.

I have a table named User with a coulmn named role. I am looking for the best way to hide parts of the view from users that have the "wrong" role for those parts of the view.

例如,我希望所有用户都能看到用户 index 页面,但我只希望具有角色 - admin 的用户能够编辑其他用户.

For example I want all users to be able to see the users index page, but i want only users with a role - admin to be able to edit other users.

所以首先我使用 filter_by 阻止了 edit 操作,但我还想要的是使 edit 按钮不出现.

So first I block the edit action using filter_by, but what I also want is make the edit button not to appear.

当前用户保存在会话中,因此查看用户角色非常简单.

The current user is saved in the session, so checking the user role is very simple.

我想问的是,除了在我想隐藏的每个按钮之前使用明显的 if 语句之外,还有什么简单的方法可以做到这一点.我认为 Rails 有一种简单的方法来做这种事情,我找不到.

What I am asking, is there an easy way to do so besides the obvious if statement before each button I want to hide. I would think that rails would have an easy way to do this type of thing, I couldn't find one.

推荐答案

如果你想稍微清理一下,你可以自己编写一个应用程序助手:

if you wanted to clean it up a tiny bit you could write yourself an application helper:

  def if_admin(user)
    if(user.is_admin? && block_given?)
      yield
      return
    end
  end

然后在你看来你可以写:

then in your view you could write:

  <% if_admin(@user) do %>
    <some admin only html />
  <% end %>

这篇关于Ruby on Rails(三)隐藏部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆