从has_many througth关系rails 5中提取中间表中的值

时间:2018-02-12 12:28:17

标签: ruby-on-rails

我正在做一个项目而且我正在通过权限,我的数据库模型或多或少是这样的:我有一个has_many通过关系,用户(完成与Devise)和组(用脚手架名称描述) :text),通过会员表,以及带有活动的组(另一个基本脚手架),通过权限,具有:

1)activity_id:参考

2)group_id:参考

3)c:boolean(要创建,如果c = true,用户所在的组可以创建活动)

4)r:boolean(对于阅读,如果r = true,用户所在的组可以看到活动)

5)u:boolean(对于update,如果u = true,用户可以编辑活动的组)

6)d:布尔值(要销毁,如果d = true,用户所在的组可以删除活动)

7)o:boolean(对于own,如果o = true,用户所在的组只能管理他创建的活动)

我需要:

1)有一些参数,以便一个组可以让用户在另一个组中犯规,即管理它。

2)在表单中,创建组时,您可以管理c, r, u, d, o对可能存在的不同活动的权限。

3)用户只能管理他创建的内容,具体取决于o是不是真或假。

2 个答案:

答案 0 :(得分:0)

我认为你的模型应该是这样的。

class User << ApplicationRecord
  has_many :owned_groups, class_name: "Group" #The groups he has created
  has_many :memberships                       #Association to groups he has joined
  has_many :groups, through: :memberships     #The groups he has joined
end

class Group << ApplicationRecord
  belong_to :owner, class_name: "User" #The user who created the group. He sets premissions.
  has_many :group_activities                       #Association to activities
  has_many :activities, through: :group_activities #The group activities
end

class Activity << ApplicationRecord
  has_many :group_activities                    #Association to groups
  has_many :groups, through: :group_activities  #The groups where this activity belongs
end

class GroupActivity << ApplicationRecord
  belongs_to :group                     
  belongs_to :activity                 
end

class Membership << ApplicationRecord
  belongs_to :user                     #This user is member of...
  belongs_to :group                    #this group.

  # This table should have the 
  # permissions for this user 
  # in this group (create activities, etc.). 
  # The Owner of the group can define these permissions
end

如果您认为这些模型是正确的,我可以继续改进答案。

答案 1 :(得分:-1)

回答你的第一个问题 - 我希望你的模型看起来像这样

class User < ActiveRecord::Base
  has_many :memberships
  has_many :activities, through: :memberships

  delegate :c, to: :memberships #this way you can access c value with user 

end

所以

user = User.find_by (id: 1)
user.c # will return the value true/false

要回答你的第二个问题 - 我需要对这一行进行一些澄清

  

我还需要知道如何从表单

创建这种关系

哪种型号之间的关系