【问题标题】:Rails cancan ability.rbRails 可以扫描能力.rb
【发布时间】:2012-09-16 09:31:18
【问题描述】:

开始学习cancan+devise

我有“用户”表(设计)

我有 'posts' 表(带有 'user_id' 字段)

我有“角色”表(带有“名称”字段)

  • 1 - 管理员
  • 2 - 用户

我有 users_roles(带有“user_id”和“role_id”)

我创建了 2 个具有“用户”角色的用户

并创建 1 个具有“管理员”角色的用户

user.rb
  has_many :posts
  has_many :users_roles
  has_many :roles, :through => :users_roles

role.rb
  has_many :users_roles
  has_many :users, :through => :users_roles

users_role.rb
  belongs_to :user
  belongs_to :role

还有一个问题:

i create ability.rb 

  def initialize(user)
    user ||= User.new
    if user.persisted?
        #loged in
        can :read, Post
        can :create, Post
        can :update, Post , :user_id => user.id
        can :destroy, Post , :user_id => user.id
    else
        #not logged
        can :read, Post
    end

在我的观点/帖子/index.html.erb

<% @posts.each do |post| %>
  <tr>
    <td><%= post.user.email %></td>
    <td><%= post.title %></td>
    <td><%= post.text %></td>
    <td><%= link_to 'Show', post %></td>
      <% if can? :update, Post %>
        <% if current_user.id == post.user.id %>
          <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <% end %>  
      <% end %>
      <% if can? :destroy, Post %>
        <% if current_user.id == post.user.id %>
          <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
        <% end %>
    <% end %>  
  </tr>

<% end %>
</table>

<br />
<!-- ???почему Post ? -->
<% if can? :create, Post %>
  <%= link_to 'New Post', new_post_path %>
<% end %>  

在这种情况下,我检查,如果用户登录 - 他可以阅读和创建、更新、销毁(如果他是 autor),如果用户没有登录(访客) - 只能阅读

但我不知道如何改变我的能力.rb 来做到这一点:

  • 我有客人(只读)
  • 我有用户(可以读取和创建、更新、销毁(如果他是作者))
  • 我有一个管理员(可以读取、创建、更新、销毁)

注意我已经有角色表(有 2 个角色)和 3 个用户(1 个具有管理员角色,2 个具有用户角色)

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    这就是我在应用程序中实现 cancan 以管理角色和来宾用户的方式。

    只需使用if user.role == role 来验证用户是否拥有正确的角色。

    class Ability
    include CanCan::Ability
    
      def initialize(user)
        user ||= User.new # guest user
        if user.role == "author"
          # 
          can :read, Post
          can :create, Post
          can :update, Post , :user_id => user.id
          can :destroy, Post , :user_id => user.id
    
          # a simple way to realize read create update and destroy is :manage
          # can :manage, Post, :user_id => user.id
    
        else
          if user.role == "admin"
            # User with role admin can manage all on all models 
            can :manage, :all
          else
            # Guest user can only read something
            can :read, Post
            # or
            # can :read, [SomeModel1, Somemodel2]
            # can :read, :all     # this means he can read all models 
    end
    

    【讨论】:

    • 我得到了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2019-10-22
    • 2014-02-04
    • 1970-01-01
    • 2011-08-16
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多