1
votes

I have one uploader that is used in the profile of three different types of users to upload their avatar or logo. I'm using carrierwave and fog here, and a S3 bucket in production. This works. Now I would like to include a link to remove the avatar/logo if that user wants to. So it should't delete the entire record of the user, just that one variable (avatar/logo). I'm using the code below.

Unfortunately, it doesn't work. What am I doing wrong here? The error: Couldn't find User without an ID referring to the controller line User.friendly.find(params[:id]).avatar.destroy. (friendly comes from the friendly_id gem.)

Users controller:

  def destroy_avatar
    User.friendly.find(params[:id]).avatar.destroy
    flash[:success] = "Avatar deleted"
    redirect_to users_url
  end

Routes:

  delete 'avatar'           =>  'users#destroy_avatar'

Link in view:

  <% if @users.avatar? %>
    <%= link_to "Remove avatar", avatar_path(@user), method: :delete %>
  <% end %>

Despite the error message @user does have a value, because it is used all over the view page for other variables that function properly.


The server log says about the request:

Started DELETE "/avatar.fakename1"
Processing by UsersController#destroy_avatar as 
  Parameters: {"authenticity_token"=>"ZYVI***AZy34jYzQ=="}
Completed 404 Not Found in 2ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find User without an ID):
  app/controllers/users_controller.rb:68:in `destroy_avatar'

And it has the following request parameters:

{"_method"=>"delete",
 "authenticity_token"=>"ZYVIEy1***DYGICxgi4jYzQ==",
 "format"=>"fakename1"}
1
What does the request look like in the Rails log? - Jordan Running

1 Answers

2
votes

When you use a rails path helper with a parameter, the route needs to reflect that.

Basically you need to do delete 'avatar/:id' => 'users#destroy_avatar', as: avatar in your routes so that you can pass a param to the path helper.