Robert Faldo
Robert Faldo

Reputation: 471

Uploading image on Rails with Carrierwave. Not updating attribute in database

I'm using the carrierwave gem to upload images

I have this form in my users view which provides an upload button for a file (image)

<%= form_for(@user, html: { multipart: true }) do |f| %>
  Update your profile pic:
  <span class="avatar">
    <%= f.file_field :avatar %>
  </span>
  <%= f.submit "Update", class: "btn btn-primary" %>
<% end %>

Here's my users controller

class UsersController < ApplicationController
  def show
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
  end

  private

  def user_params
    params.require(:user).permit(:avatar)
  end
end

When I click the submit button on the form from the browser, I get this http request come through.

Started PATCH "/users/1" for 127.0.0.1 at 2018-07-05 13:15:39 +0100
Processing by UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"VXaEvnTD7nl+2d/0n1+iB/zwRX+Mf3nbMt0/Qr7m/nYpTmyXCxih981pIbGKGT9qdSfB7zyB6l
CKGdA9uiLouw==", "user"=>{"avatar"=>#<ActionDispatch::Http::UploadedFile:0x00007fbf2a794af0 @tempfile=#<Tempfile:/var/folders
/42/plkmf9zn755b0lvwc2_5k30c0000gn/T/RackMultipart20180705-37847-7s1tba.png>, @original_filename="Screen Shot 2018-07-03 at 1
0.23.17.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"user[avatar]\"; filename=\"Screen S
hot 2018-07-03 at 10.23.17.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Update", "id"=>"1"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], [
"LIMIT", 1]]
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
No template found for UsersController#update, rendering head :no_content
Completed 204 No Content in 161ms (ActiveRecord: 0.6ms) 

But nothing is updated in the database (i.e. the avatar attribute for the current user still has a value of nil). I also can't see that the image has been saved anywhere.

Upvotes: 0

Views: 595

Answers (1)

d1ceward
d1ceward

Reputation: 1035

It's your controller update method which is incomplete, for example :

  def update
    user = User.find(params[:id]) # Set user
    if user.update(user_params) # Save to database
      # Success, redirect to show/index/whatever
    else
      # Fail, render form again
    end
  end

And i recommend you to read this: http://guides.rubyonrails.org/action_controller_overview.html

Upvotes: 1

Related Questions