【发布时间】:2017-07-04 06:20:05
【问题描述】:
我有两个模型通过连接模型连接。连接模型存储了一个附加属性value,它是一个布尔值A Role 有许多Permissions 到RolePermission,RolePermission 存储Role 是否可以执行Permission 指示的操作。
每个Role 都应该有一个RolePermission 记录,每个Permission(其中大约有10 个)。
但是,我在创建表单时遇到了问题。我希望每个Permission 都有一个复选框,用于指示RolePermission 的value 属性的布尔值。
型号
class Role < ApplicationRecord
has_many :role_permissions, dependent: :destroy
has_many :permissions, through: :role_permissions
accepts_nested_attributes_for :role_permissions
end
class RolePermission < ApplicationRecord
belongs_to :role
belongs_to :permission
end
class Permission < ApplicationRecord
has_many :role_permissions
has_many :roles, through: :role_permissions
end
表格列
Roles
name: string
description: string
Permissions
name: string
description: string
RolePermissions
role: references
permission: references
value: boolean
视图/角色/_form.html.erb
<%= form_for [@chronicle, @role], url: url do |f| %>
...
<%= f.fields_for :role_permissions, Permission.all do |ff| %>
???
<%= ff.label :name %>
<%= ff.check_box :value %>
???
<% end %>
<%= f.submit text, class: 'btn btn-primary btn-block' %>
<% end %>
控制器/roles_controller.rb
class RolesController < ApplicationController
...
def create
@chronicle = Chronicle.find(params[:chronicle_id])
@role = @chronicle.roles.build(role_params)
???
@role_permissions = @role.role_permissions.build
???
if @chronicle.save
flash[:success] = 'Role successfully created.'
redirect_to chronicle_role_url(@chronicle, @role)
else
render 'new'
end
end
private
def role_params
params.require(:role).permit(:name, :description, role_permission_attributes: [] )
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5