Reputation: 383
the following is my code for one of my controllers I have written for my Rails show reviewing application. Note that I that I did not use Devise for user auth.
The problem I am facing right now is that I want the user (pco) to only be able to update the show if he/she is the one which originally uploaded it. Here, authorized_as_pco_to_show
can determine that but it needs the @show
to be passed into it as a parameter. Therefore, I cannot use before_action
.
The way I have it right now is to put this authorized_as_pco_to_show
method at the start of every action which only allows for the correct pco to access it. I was wondering if there would be a better way of doing this. Any help would be much appreciated!
def update
authorized_as_pco_to_show @show
respond_to do |format|
if @show.update(show_params)
format.html { redirect_to @show, notice: "Show was successfully updated." }
format.json { render :show, status: :ok, location: @show }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @show.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 0
Views: 910
Reputation: 10898
You can pass parameters to before actions if required. Instead of this:
before_action :authorized_as_pco_to_show
You can use:
before_action do
authorized_as_pco_to_show @show
end
However, as mentioned in the comments, you'll need to get that show from somewhere. Assuming you have another before_action along the lines of load_show
which loads it into an instance variable, you can then just use that within your other before_action. Something like this:
before_action :load_show, :authorized_as_pco_to_show
# your actions here
private
def load_show
@show = Show.find(params[:id])
end
def authorized_as_pco_to_show
@show.authorized? # replace with whatever your checks are
end
Upvotes: 2