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.

jcuenod
  • 55,835
  • 14
  • 65
  • 102

3 Answers3

0

Wouldn't you be able to do:

def create
 @mymodel = MyModel.new
 authorize @mymodel
 @mymodel.update_attributes(mymodel_params)
end
natsumi
  • 76
  • 3
0

For pundit, you can call the model name in it without it being a instance variable or symbol.

ex. Posts

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

The pundit section on this application will show it in action.

AGirlThatCodes
  • 575
  • 7
  • 21
  • is this pdf legal? Also, could be wrong but I'm pretty sure that this is doing the same thing as `authorize :post` – jcuenod Mar 24 '15 at 14:17
0

The correct way to do this is like this:

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

This way, you can use the properties set in your @mymodel instance, for example:

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

So your data is not persisted before you authorize the record and you can authorize the record based on what the data will be.

Saul
  • 911
  • 1
  • 8
  • 19