简体   繁体   中英

Allow Admin to edit other user's pins - Rails

I added an admin boolean column to my user table and toggled my user to yes. I changed the following code so that the "edit" button shows to teh admin for all pins:

<% if current_user == pin.user || current_user.admin? %>
  <p>
      <%= link_to 'Edit', edit_pin_path(pin) %>
      <%= link_to content_tag(:i, "", class:"icon-trash"), pin, method: :delete, data: { confirm: 'Are you sure?' } %>
  </p>
<% end %> 

When I try to edit a pin, I get an error: Couldn't find Pin with id=37-outer [WHERE "pins"."user_id" = 1] I believe this is because of the pins controller, but I haven't figured out how to correctly change it to allow admins to edit. Here's my controller:

def edit
@pin = current_user.pins.find(params[:id])

end

I have a feeling this is an easy fix that I'm just missing.

you are scoping pins to the current_user which is the reason why you're getting the error. Try changing the code that finds the pin to

klass = Pin
klass = klass.where(user_id: current_user.id) unless current_user.admin?
@pin  = klass.find(params[:id])

alternatively, if this is something you'll be using in a lot of places, it may be good to define a class method instead

# app/models/pin.rb
def self.find_for_user(pin_id, user)
  user.admin? ? find(pin_id) : user.pins.find(pin_id)
end

# in your controller
@pin = Pin.find_for_user(params[:id], current_user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM