Ruby on rails 设备/CanCan-如何拆分控制器';用户角色的操作?
我在我的应用程序中有一个名为“喜欢”的动作,它是book controller中的一个动作,也就是说,我的Desive用户可以“喜欢”一本书,并将其添加到他们的个人资料中 在CanCan中,我希望角色==“author”的用户能够创建、更新和删除他们自己的书籍,这很好。问题是我希望任何用户都能“喜欢”任何一本书。当我添加这一功能时,我让用户“管理”所有书籍——我如何限制它,使所有用户都可以喜欢/不喜欢书籍,但作者用户可以管理他们拥有的书籍 任何提示都将不胜感激 能力.rbRuby on rails 设备/CanCan-如何拆分控制器';用户角色的操作?,ruby-on-rails,devise,cancan,Ruby On Rails,Devise,Cancan,我在我的应用程序中有一个名为“喜欢”的动作,它是book controller中的一个动作,也就是说,我的Desive用户可以“喜欢”一本书,并将其添加到他们的个人资料中 在CanCan中,我希望角色==“author”的用户能够创建、更新和删除他们自己的书籍,这很好。问题是我希望任何用户都能“喜欢”任何一本书。当我添加这一功能时,我让用户“管理”所有书籍——我如何限制它,使所有用户都可以喜欢/不喜欢书籍,但作者用户可以管理他们拥有的书籍 任何提示都将不胜感激 能力.rb def initial
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 %>
存在违反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
#Registered user
can :create, Like
can :destroy, Like.where(user_id: user.id)
名单如下:
Book.find(id).likes # list all likes for book
User.find(id).likes # list all likes made by user
权限应如下所示:
class Book < ActiveRecord::Base
has_many :likes, dependent: :destroy
end
class Like < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
#Registered user
can :create, Like
can :destroy, Like.where(user_id: user.id)
如果你需要更多关于这一认识的信息,尽管问我。我将扩展我的答案。谢谢!我终于开始着手做这件事了。我在上面更新了我的喜欢控制器和我的书展(在那里用户应该能够添加/删除喜欢)。我似乎做得不对。我需要喜欢/不喜欢的行为而不是创造/破坏吗?我发现这也很有帮助!