设备/ CanCan - 如何按用户角色拆分控制器的操作?

时间:2014-11-04 03:10:41

标签: ruby-on-rails devise cancan

我的应用程序中有一个名为“like”的动作,它是书籍控制器内部的动作,即我的Devise用户可以“喜欢”将其添加到其个人资料中的书。

在CanCan中,我希望具有角色==“作者”的用户能够创建,更新,删除自己的书籍,这样可以正常工作。问题是我希望任何用户能够“喜欢”任何书籍。当我添加该功能时,我会让用户“管理”所有图书 - 如何限制它以便所有用户都可以喜欢/不同于图书,但作者用户可以管理他们拥有的图书?

任何提示都表示赞赏!

ability.rb

def initialize(user)
    # Guest User 
    can :read, :all
    unless user 
      can :read, :all
    else
      # All registered users
      can :read, :all  
      can :manage, Like
      can :manage, Book 
      # Authors 
      if user.role == 'author'
        can :read, :all
        can :create, Recommendation
        can :manage, Recommendation do |r|
            user && r.user == user
        end
        can :create, Book
        can :manage, Book do |b|
            user && b.user == user
            end 
      # Admins
      elsif user.role == 'admin'
        can :manage, :all
      end
    end 
  end  

喜欢控制器

before_action :set_project
load_and_authorize_resource

def create
    if Like.create(liked: @book, user: current_user)
      redirect_to @book, notice: 'Book has been favorited'
    else
      redirect_to @book, alert: 'Something went wrong'
    end
  end
  def destroy
    Like.where(liked_id: @book.id, user_id: current_user.id).first.destroy
    redirect_to @book, notice: 'Book is no longer in favorites'
  end

  private

  def set_project
    @book = Book.find(params[:book_id] || params[:id])
  end
  def like_params
      params.require(:like).permit(:user_id, :book_id)
  end
end
书展

<% unless current_user.liked_books.exists?(id: @book.id) %>
<%= link_to 'Add to likes', like_path, method: :post %>
<% else %>
<%= link_to 'Remove from likes', like_path(@book), method: :delete %>
<% end %>

1 个答案:

答案 0 :(得分:1)

违反了CRUD原则。 首先从book_controller.rb中删除like操作。 这是一个喜欢,而不是一本书。此操作应该是like_controller.rb中的create。 关系应该是这样的:

class Book < ActiveRecord::Base
  has_many :likes, dependent: :destroy
end

class Like < ActiveRecord::Base
  belongs_to :book
  belongs_to :user
end

现在,添加喜欢预订,只需创建它,与用户和图书相关联。

Like.new(book_id: params[:book_id], user_id: params[:user_id])

列表赞:

Book.find(id).likes # list all likes for book
User.find(id).likes # list all likes made by user

权限应该是这样的:

#Registered user
can :create, Like
can :destroy, Like.where(user_id: user.id)