Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3094

paperclip image is not saving

I am using paperclip gem to upload the images but the image is not saving.

Here is my Photo model:

class Photo < ApplicationRecord
belongs_to :room


has_attached_file :image, styles: {medium: '300x300>', thumb: '100x100>'},
                  :path => ':rails_root/public/images/:id/:style/:filename',
                  :url => '/images/:id/:style/:filename'
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
    # do_not_validate_attachment_file_type :image
end

Room model:

class Room < ApplicationRecord
    belongs_to :user
    has_many :photos
end

form:

<%= file_field_tag "images[]", type: :file, multiple: true %>

controller:

def create
    @room = current_user.rooms.build(room_params)

    if @room.save

        if params[:images]
            params[:images].each do |image|
                @room.photos.create(image: image)
            end
        end

        @photos = @room.photos
        redirect_to edit_room_path(@room), notice: 'Saved...'
    else
        render :new
    end
end

Only room is saving but not the photo model. I tried to save images using relationship but not working even without relationship image is not saving. Can anyone help me?

Upvotes: 0

Views: 213

Answers (3)

Manzurul Hoque Rumi
Manzurul Hoque Rumi

Reputation: 3094

Problem solved. I had to upgrade ImageMagick. Thank you all

Upvotes: 0

Gaurav
Gaurav

Reputation: 121

It's hard to suggest to a solution like this. Change create to create! to raise an exception and then you can debug better.

def create
    @room = current_user.rooms.build(room_params)

    if @room.save

        if params[:images]
            params[:images].each do |image|
                @room.photos.create!(image: image)
            end
        end

        @photos = @room.photos
        redirect_to edit_room_path(@room), notice: 'Saved...'
    else
        render :new
    end
end

You can also try removing styles key to see if something is wrong with generating other images, maybe ImageMagick is not installed.

Upvotes: 1

Imre Raudsepp
Imre Raudsepp

Reputation: 1178

Hard to say where exactly problem lies. Looks like u using paperclip has_attached_file method. Probably your uploaded image does not meet validation and its type isnt like something "image/jpg", "image/jpeg", "image/png", "image/gif" etc types. Can u provide what image u trying to save.

Upvotes: 0

Related Questions