【发布时间】:2020-04-27 15:38:15
【问题描述】:
我正在开发一种基于属性和基于角色的访问控制的授权管理。我需要将角色与(用户)组相关联,并将可用功能与(用户)组相关联。 Role 类和 Feature 类都不存在,它们被定义为从 Parameter 类中提取的选项列表。总而言之,我尝试在 Parameter 类和 Group 类之间创建 2 个 HABTM 关系。
关系建立在角色编辑表单中。这是我的代码:
<div class="row mat-form-row">
<div class="mat-form-field col-md-6">
<%= f.label :roles, t('Roles'), class: "mat-form-field-label" %>
<%= f.collection_select :role_ids, list_of_user_roles, :id, :name, { }, { multiple: true, class: "mat-input-element select2-candidate" } %>
</div>
<div class="mat-form-field col-md-6">
<%= f.label :feature, t('Features'), class: "mat-form-field-label" %>
<%= f.collection_select :feature_ids, list_of_app_features, :id, :name, { }, { multiple: true, class: "mat-input-element select2-candidate" } %>
</div>
</div>
</div>
其中 list_of_users_roles 和 list_of_app_features 是从参数表中提取的。
使用默认结构创建了一个链接表来存储 n-n 关联:
class CreateTableGroupsParameters < ActiveRecord::Migration[5.2]
def change
create_table "groups_parameters", id: :serial do |t|
t.references :parameter, index: true
t.references :group, index: true
t.boolean "is_active", default: true, comment: "As nothing can be deleted, flags objects removed from the knowledge base"
t.datetime "active_from", default: -> { 'current_date' }, comment: "Validity period"
t.datetime "active_to"
t.timestamps
end
end
end
已链接模型并设置了强大的参数:
##group.rb
has_and_belongs_to_many :roles, :class_name => "Parameter"
has_and_belongs_to_many :features, :class_name => "Parameter"
##parameter.rb
has_and_belongs_to_many :groups
##groups_controller
# Never trust parameters from the scary internet, only allow the white list through.
def group_params
params.require(:group).permit(:name, :description, :role, :territory_id, :organisation_id, :created_by, :updated_by, :code, :role_ids => [], :feature_ids => [])
end
为每个关系(角色或功能)分别成功创建链接。但是当两者一起实现时,更新一个值列表只会起作用。最糟糕的是,更新另一个会删除之前的更新!
您有解决此问题的建议吗? 非常感谢!
【问题讨论】:
-
请在双向提交表单时显示 Web 服务器控制台消息。它将显示提交的内容及其结构,以便我们进行比较。
-
“该功能运行良好......”完全含糊。请在stackoverflow.com/help/how-to-ask 阅读问题指南。如果您将问题描述为好像我们对您的应用一无所知,这会有所帮助,因为我们不知道!大声笑或想象描述将你的鞋系在一个看不见的人身上。即非常详细和简单。
标签: ruby-on-rails activerecord has-and-belongs-to-many