【问题标题】:Rails: Current_user should only see records from his/her own group. How do I do this?Rails:Current_user 应该只能看到他/她自己组的记录。我该怎么做呢?
【发布时间】:2011-09-14 09:45:58
【问题描述】:

如何构建我的 Rails 3.x 应用程序,以便登录的用户只能看到与他所属的组关联的记录?

例如, (足球主题)

想象一下这些模型:

一个团队模型,代表 30 支职业橄榄球队中的每一支。

一个用户模型,使用设计进行身份验证。每个用户都有一个 team_id 关联。

一个 Player 模型,代表 NFL 中的每个球员:name:string, team_id:integer。

每个用户都是主教练,并且应该只能在 player#index 中看到自己的球员。 Rails 知道这一点,因为主教练(用户)有一个与他相关联的 team_id,球员也是如此。

现在,只有两个控制器(团队、玩家),手动重新键入 index 和 CRUD 方法以仅显示 current_user 的关联记录似乎相当容易。

def index
  @players = Player.where(current_user.team_id = ?, 'player.team_id')
end

但假设您有 6-10 个控制器: 门票, 交易, 雇员, 合同, ETC..... (都有一个 team_id 关联)

Rails 是否有一种全局方式只显示与 current_user 的团队相关的记录?
还有……Rails 如何防止用户在 URL 中输入随机 ID 以查找与他的 team_id 无关的记录。 (想象一下红皮队教练输入http://www.thesite.com/players/224/edit)并能够编辑一名 player_id = 224 的牛仔队球员。

谢谢。

【问题讨论】:

    标签: ruby-on-rails devise associations


    【解决方案1】:

    如果所有模型都有一个 team_id 属性,你需要在你的应用程序控制器中定义一个前置过滤器,如下所示:

    def identify_team
      @team = current_user.team
    end
    

    在每个其他控制器中,您应该通过引用团队变量来确定查询范围,例如

    def index
      @players = @team.players.all
    end
    

    理论上,您可以通过控制器中的 current_user (current_user.team.players.all) 确定范围,但这不是最佳实践。

    问候

    罗宾

    【讨论】:

    • 为什么在控制器中使用 current_user 是一种不好的做法?
    • 不使用current_user,而是创建长关联链
    【解决方案2】:

    您可以为此使用关联。每个具有用户关系的表在 Rails 中也可以具有模型关联。

    所以通过关系 current_user.players 等你可以得到。

    【讨论】:

      【解决方案3】:

      试着看看下面的railscasts,ryan bates 很好地解释了这些东西。还可以查看teachmetocode 网站。所有这些链接将为您提供关联的基础以及如何设置不同模型之间的数据库关联,以便您可以实现您想要的。这些链接应该可以帮助您入门:

      Self-Referential Association

      Polymorphic Association

      Two Many-to-Many

      HABTM Checkboxes

      Embedded Association

      ActiveRecord::Relation Walkthrough

      Active Record Queries in Rails 3

      Many to Many Associations in Ruby on Rails – A Teach Me To Code Tutorial

      【讨论】:

        猜你喜欢
        • 2012-05-26
        • 2021-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多