Rails,Models和" Projects"作用域

时间:2016-12-11 12:27:08

标签: ruby-on-rails ruby authorization

我使用Rails 5.0.0.1和自定义身份验证/授权系统(类似于Devise / CanCan)。

我正在开发一个Rails应用程序,我正在寻找一些关于如何根据用户是否属于"组"来显示/隐藏数据的建议。或"项目"。

应用程序:基本上,用户可以突出显示"文章文章的行。首先向它们呈现文章内容的视图(即其行的索引)。他们可以选择要突出显示的行。当突出显示某行时,任何用户都可以单击该行以显示该行的注释部分。

Article has_many Lines
Line has_many Highlights
Highlight has_many Comments
User has_many Highlights
User has_many Comments

Highlight belongs_to User
Comments belongs_to Highlight
Comments belongs_to User

现在我想添加" Group Project"功能。用户选择要在组项目中使用的文章。他邀请其他用户参与这个项目。受邀用户可以突出显示和评论,但所有突出显示和评论仅对该项目的用户可见。

我的想法是创造'范围'。默认情况下,对于所有文章,精彩集锦和评论,范围都是“公开”。任何用户都可以登录并查看这些文章,重点,评论。但是用户也可以访问他的一个Group Projects并查看(可能是相同的)带有“私有”范围的高亮,评论等的文章。这就会出现一个Line可以有多个高亮显示和不同范围的注释的问题。文章的重点/评论有一个公共版本和多个私有版本。

我的问题是如何有效地处理这些多个实例?我应该为每个项目创建新的Lines实例吗?这似乎是数据库中不必要的重复。我应该在控制器或模型中根据project_id或类似的东西放置一些条件吗?

我知道处理"用户组"有多个宝石,但它们通常用于授权。我希望用户能够创建任意数量的项目,每个项目都有自己的被邀请者,重点和评论。

1 个答案:

答案 0 :(得分:0)

您可以将字段project_id添加到highlightscomments表格和设置关联:

class User < ActiveRecord::Base
  has_and_belongs_to_many :projects
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_many :highlights
  has_many :comments
end

class Line < ActiveRecord::Base
  has_many :comments
  has_many :highlights
end

class Highlight < ActiveRecord::Base
  belongs_to :project
  belongs_to :line
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :project
  belongs_to :highlight
  belongs_to :user
  belongs_to :line
end

然后您将能够通过

访问所有(比如说)亮点
Highlight.all

所有公开亮点

Highlight.where(project: nil)

的具体@line@project的所有要点
@line.highlights.where(project: @project)

此外,为了节省数据库空间并提供一定的灵活性,您可以将belongs_to_idbelongs_to_type字段添加到comments表中,并将Comment模型更新为< / p>

class Comment < ActiveRecord::Base
  def self.belongs_to(types)
    types.each do |type|
      super type, foreign_key: "belongs_to_id"
    end
    validates_inclusion_of :belongs_to_type, in: types.map { |type| "#{type.capitalize}" }
  end

  belongs_to [:project, :highlight, :user, :line]
end

# didn't test