使Cancan的load_and_authorize_resource在自定义创建动作中工作 [英] Getting Cancan's load_and_authorize_resource working within a custom create action
问题描述
试图在我的应用中设置 Cancan ,但遇到我的 PostsController
遇到的麻烦。
Trying to set up Cancan within an app of mine and having trouble with my PostsController
.
简而言之,当创建 Post
后,我希望它与 current_user
,因此我的创建动作如下所示:
In a nutshell, when a Post
is created I'd like it associated with the current_user
so my create action looks something like this:
class PostsController < ApplicationController
before_filter :login_required, :except => [:index, :show]
load_and_authorize_resource
...
def create
# @post = Post.new(params[:post]) # <-- covered by load_and_authorize_resource
@user = current_user
@post = @user.posts.create(params[:post])
respond_to do |format|
...
end
...
end
我不确定 load_and_authorize_resource
打算做什么(不是显而易见的)。但是在这种情况下呢?是否需要以某种方式覆盖 load_and_authorize_resource
?还是有另一种(更好的阅读方式)去加载 @user
然后创建 @post
?
I'm not exactly sure what load_and_authorize_resource
is intended to do (other than the obvious). But what about in a situation like this? Do I need to override the load_and_authorize_resource
for the create action somehow? or is there another (read: better) way to go about loading the @user
and THEN creating the @post
?
推荐答案
一个简单的解决方案是使用嵌套资源,而不是创建自定义操作
A simpler solution to your problem would be to use a nested-resource, rather than creating a custom action
直接取自CanCan Wiki:
Directly taken from the CanCan Wiki:
1.4,也可以通过方法嵌套,通常是
为current_user方法。
As of 1.4, it's also possible to nest through a method, this is commonly the current_user method.
class ProjectsController < ApplicationController
load_and_authorize_resource :through => :current_user
end
这里所有内容都将通过current_user.projects关联进行加载。
Here everything will be loaded through the current_user.projects association.
这也应该更安全,因为帖子的加载将通过关联完成,以便控制器中的其他操作
This should be safer as well, as loading of a post will be done through the association for other actions in your controller
这篇关于使Cancan的load_and_authorize_resource在自定义创建动作中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!