【问题标题】:Ruby on Rails - Assign View and/or edit to different users (in same team)Ruby on Rails - 将视图和/或编辑分配给不同的用户(在同一个团队中)
【发布时间】:2017-07-13 23:12:08
【问题描述】:

在我的应用程序中,我有模型 Team User Post

class User < ActiveRecord::Base
  has_many :posts
  belongs_to :team

class Team < ActiveRecord::Base
  has_many :users

class Post < ActiveRecord::Base
  belongs_to :user

在我的_form.html.haml 我有这部分:

- User.where(team_id: current_user.team_id).each do |user|
  %p=user.name

显示同一团队中的所有用户。

当一个用户 (在同一个团队中)写一个post。我希望他们能够分配可以编辑和/或查看帖子的用户。

这意味着用户可以将一些用户分配给仅查看,而将一些用户分配给查看和编辑

我该怎么做?最好的方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 model assign


    【解决方案1】:

    我会创建另一个模型,可能如下所示:

    class Permission < ActiveRecord::Base
      belongs_to :post
      belongs_to :user
    
    class User < ActiveRecord::Base
      has_many :posts
      has_many :permissions
      belongs_to :team
    
    class Team < ActiveRecord::Base
      has_many :users
    
    class Post < ActiveRecord::Base
      has_many: permissions
      belongs_to :user
    

    权限模型可能包含“id”、“post_id”、“user_id”、“editable”和“viewable”等字段(最后两个字段为布尔值)。提交时,您可以创建用户为帖子选择的尽可能多的权限角色。如果@user.post.permission == post.user_id && @user.permission.editable,您将只允许人们进行编辑?两者都返回为真(或类似的东西,不确定您的应用程序的其余部分是如何设置的)

    【讨论】:

    • 谢谢@Michael。在我的posts#_form.html.haml 中,我还为permissions 添加了一个单独的form 或者我可以在同一个form 中进行分配,如果可以的话怎么办?
    • 您指的是嵌套表单。查看导轨指南的第 9 节(嵌套形式):guides.rubyonrails.org/form_helpers.html#nested-forms。嵌套表单的 stackoverflow 上也有很多很好的参考。
    【解决方案2】:

    你可以创建一个实例方法并使用它

    class User < ActiveRecord::Base
      has_many :posts
      belongs_to :team
    
      def team_members
        User.where(team_id: team_id)
    
        # If you dont want current_user/self in the result you can use
        # User.where(team_id: team_id).where.not(id: id) 
      end
    end
    

    现在你可以使用它了

    - current_user.team_members.each do |user|
    

    另外,您可以在下拉菜单中使用它

    = f.collection_select :user_id, current_user.team_members, :id, :name
    

    问。如何将帖子的查看和/或编辑和查看分配给同一团队中的每个用户?

    A.您可以检查当前用户是否属于帖子作者的团队

    类似

    - @posts.each do |post|
      - if post.user.team_members.include?(current_user)
        = link_to "Edit", edit_post_path(post)
    

    【讨论】:

    • 感谢@Deepak。这只是获取/显示users 对吗?如何将 postView 和/或 Edit & View 分配给同一团队中的每个用户?
    猜你喜欢
    • 2022-08-15
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多