Search code examples
ruby-on-rails-4paperclipsti

Rails 4 Paperclip not saving image to db with STI


I can not get paperclip to save images to the database, I have used different paperclip versions (3.5.0, 4.2 and from the git repo). At present I am using 4.2 as recommended in the Gem's Docs.

class Instructor < ActiveRecord::Base
  #also tried having the has_attached method in this class
end

class Driver < Instructor
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" },           :default_url => "/images/:style/missing.png"
  validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
end

schema.rb

create_table "instructors", force: true do |t|
....
t.string   "avatar_file_name"
t.string   "avatar_content_type"
t.integer  "avatar_file_size"
t.datetime "avatar_updated_at"
end

now in my drivers/edit page:

<%= simple_form_for (@driver), id: "step_form", :html => { :multipart => true }, :class => "form-group", url: wizard_path do |f| %>
          ...
          <div class="form-group">
            <label>Upload an Image</label>
            <div class="span7"><%= f.file_field :avatar %>
            </div>
          </div>

          <div class="actions">
            <button type="submit" class="btn btn-success">Next</button>
            or <%= link_to "skip this step", next_wizard_path %>
          </div><br>
        <%end %>

in my Drivers Controller

   class DriversController < InstructorController
...  

def update
    @driver = current_instructor
  if @driver.update(permitted_params)
    flash[:success] = "Profile updated"
    redirect_to :dashboard
  else
    flash[:error] = "Profile not updated"
    render :edit
  end
end

private

  def permitted_params
    params.require(:driver).permit(..., :avatar)
  end  

end

and the payload from the post action from the browser

... ------WebKitFormBoundaryIV0A8q3XIQ4pTWFr Content-Disposition: form-data; name="driver[avatar]"; filename="darth vader.jpeg" Content-Type: image/jpeg

However the image does not get saved to db, ideas anyone?

I know paperclip is working in the project as I have it on another model not using STI.


Solution

  • The issue was in the permitted params, it should refer to instructor and not driver as per below:

    def permitted_params
      params.require(:instructor).permit(..., :avatar)
    end