使用Rolify的Rails 4 - 分配范围角色

时间:2016-08-15 00:54:09

标签: ruby-on-rails roles rolify

我正在试图弄清楚如何在我的Rails 4应用程序中分配作用域角色。

我有用户,角色和组织的模型。

用户表包含所有用户。角色表具有用于创建角色的CRUD(即访客,学生等)。组织表列出了所有组织,所有角色都将分配给具有组织范围的用户。

我的模特是:

用户

rolify strict: true # strict means you get true only on a role that you manually add
attr_accessor :current_role

作用

scopify
  has_and_belongs_to_many :users, join_table: "users_roles"
  belongs_to :resource, :polymorphic => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

组织

resourcify

我制作了一个名为assign_roles_controller.rb的控制器。

它有:

def index
    @roles = Role.all 
    @users = User.all
end


  def create
    user = User.find(params[:users])
    role = Role.find(params[:roles])
    organisation = Organisation.first # once I get this working, I'll find the relevant organisation that the user is related to)

    user.add_role role.name, organisation

    flash[:notice] = "Successfully created"
    redirect_to action: :index
  end

在我的分配角色索引中,我正在尝试:

<%= form_tag(url: '/assign_roles', method: :post ) do |f| %>
<div class="row">
  <div class="col-md-3 col-md-offset-2">
    <%= select_tag "users", options_from_collection_for_select(@users, "id", "formal_name"), { class: "chosen-select form-control" } %>
    </div>

<!-- # roles -->

  <div class="col-md-3 col-md-offset-1">
    <%= select_tag "roles", options_from_collection_for_select(@roles, "id", "name"), :class => 'chosen-select form-control' %>
    </div>
</div>
<%= submit_tag(value = "Save changes") %>
<% end %>

当我尝试所有这些时,我希望能够检查是否已为用户分配了一个角色,作用于组织。

按照rolify文档中的示例,我尝试:

u.has_role? :asdf, Organisation.first

我收到错误消息:

  Organisation Load (2.6ms)  SELECT  "organisations".* FROM "organisations"  ORDER BY "organisations"."id" ASC LIMIT 1
NoMethodError: undefined method `has_role?' for #<User:0x007fee2b4a1098>
Did you mean?  has_attribute?

我可以从控制台看到,角色表已由assign roles表单更新。我担心这是不正确的,因为该角色应该可以分配给所有组织 - 但每次分配时,给予该角色的用户应该将该角色限定为相关组织。此表条目看起来不正确,因为现在它以组织ID为1进行更新。

Role.last
  Role Load (4.9ms)  SELECT  "roles".* FROM "roles"  ORDER BY "roles"."id" DESC LIMIT 1
 => #<Role id: 9, name: "asdf", resource_id: 1, resource_type: "Organisation", created_at: "2016-08-15 00:03:25", updated_at: "2016-08-15 00:03:25", enduring?: false, expiry_date: nil, display_name: nil> 

谁能看到我出错的地方?

我想知道我是否需要为AppRoles创建一个新表(是我想在应用程序中创建的角色)。然后,我当前拥有的Roles表可用于保存为用户创建的每个角色的实例,并为其分配组织范围。这种方法是否合理?

0 个答案:

没有答案