回形针图像未保存

时间:2018-04-14 07:45:25

标签: ruby-on-rails paperclip

我使用paperclip gem上传图片,但图片没有保存。

这是我的照片模型:

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

房间型号:

class Room < ApplicationRecord
    belongs_to :user
    has_many :photos
end

形式:

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

控制器:

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

只有房间可以保存,但不是照片模型。我尝试使用关系保存图像,但即使没有关系图像也不能保存。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:0)

很难说问题到底在哪里。看起来你使用paperclip has_attached_file方法。可能你上传的图片不符合验证,它的类型不像是#34; image / jpg&#34;,&#34; image / jpeg&#34;,&#34; image / png&#34;,&#34 ;图像/ GIF&#34;等类型。你可以提供你试图保存的图像。

答案 1 :(得分:0)

很难建议像这样的解决方案。 将创建更改为创建!以引发异常,然后您可以更好地进行调试。

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

你也可以尝试删除样式键以查看生成其他图像是否有问题,可能没有安装ImageMagick。

答案 2 :(得分:0)

问题解决了。我不得不升级ImageMagick。谢谢大家