0

I am creating and updating objects, my controller has:

def create
    @mymodel = MyModel.create mymodel_params
    authorize @mymodel
end

I need to authorize create so I have added authorize @mymodel but surely this should come first? The problem is what parameter do I give authorize?

I could do

authorize :mymodel

but it seems that this is not the way Pundit is supposed to be used inside controllers that have associated policies. What is the correct way to authorize here? Apologies if I missed it in the docs.

4

3 回答 3

0

难道你不能这样做:

def create
 @mymodel = MyModel.new
 authorize @mymodel
 @mymodel.update_attributes(mymodel_params)
end
于 2015-03-17T20:46:45.007 回答
0

对于权威人士,您可以在其中调用模型名称,而不是实例变量或符号。

前任。帖子

class PostPolicy < ApplicationPolicy

  def create?
    user.admin?
  end

end


class PostsController < ApplicationController
  expose(:post)

  def create
    authorize post
    post.save
    respond_with(post)
  end

 end

此应用程序的权威部分将展示它的实际应用。

于 2015-03-19T14:11:29.913 回答
0

正确的方法是这样的:

def create
  @mymodel = MyModel.new(mymodel_params)
  authorize @mymodel
  @mymodel.save
end

这样,您可以使用在 @mymodel 实例中设置的属性,例如:

class MyModelPolicy
  def create?
    @record.user == @user
  end
end

因此,在您授权记录之前,您的数据不会被保留,您可以根据数据的内容授权记录

于 2016-05-21T02:19:18.687 回答