Rails - 如何在不重复的情况下为多个角色声明 attr_accessible [英] Rails - How to declare attr_accessible for multiple roles without duplication

查看:46
本文介绍了Rails - 如何在不重复的情况下为多个角色声明 attr_accessible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以为多个角色声明 attr_accessible 而不需要大量重复?

Is there a way to declare attr_accessible for multiple roles without a ton of duplication?

如果我有多个用户角色,并且每个角色都可以编辑不同的属性子集,那么我的 attr_accessible 声明如下所示:

If I have several user roles, and each role is allowed to edit a different subset of attributes, here's what my attr_accessible declaration looks like:

attr_accessible :first_name, :last_name, :active, :as => :admin
attr_accessible :first_name, :last_name, :as => :manager
attr_accessible :first_name, :last_name, :as => :guest

我愿意

  • A) 定义一组可访问的属性,可以在它们之间共享不同的角色或
  • B) 定义一组可以访问相同角色的角色属性

这可能吗?

推荐答案

所有 ruby​​ 代码仍然只是 ruby​​ 代码......因此是无限可破解的.例如

All ruby code is still just ruby code... and is thus infinitely hackable. eg

ROLES = [:admin, :manager, :support, :user, :guest]
ACTIVE_ROLES = [:admin, :support]
ROLES.each do |role|
   fields = [:first_name, :last_name]
   fields += [:active] if ACTIVE_ROLES.include?(role)
   attr_accessible *fields, :as => role
end

这篇关于Rails - 如何在不重复的情况下为多个角色声明 attr_accessible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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