简体   繁体   English

Rails 5回形针从URL保存图像

[英]Rails 5 Paperclip Save Image from URL

I'm a total Rails newbie so apologies if this is a simple question, but I've been unable to find a clear answer. 我是一个Rails新手,所以很抱歉,如果这是一个简单的问题,但是我一直找不到明确的答案。 I'm trying to allow a user to attach an image to a post either by uploading a file or entering the URL of an image using the Paperclip gem. 我试图允许用户通过上传文件或使用Paperclip gem输入图像的URL,将图像附加到帖子上

File upload works fine, but using the URL method I receive a 'No handler defined' error 文件上传正常,但是使用URL方法时,我收到“未定义处理程序”错误

link.rb 链接

require "open-uri"

class Link < ApplicationRecord
    attr_reader :image_from_url
    has_attached_file :image, styles: { medium: "600x600>", thumb: "100x100#" }, default_url: "/images/:style/missing.png"
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

    def image_from_url=(url)
        self.image = URI.parse(url)
        @image_from_url = url
    end
end

_form.html.erb _form.html.erb

<%= form_with(model: link, local: true) do |form| %>
    <%= form.file_field :image, id: :link_image %>
    <%= form.text_field :image, id: :link_image_url %>
<% end %>

links_controller.erb links_controller.erb

def create
    @link = current_user.links.build(link_params)
end

def link_params
  params.require(:link).permit(:title, :url, :description, :image, :slug)
end

I must confess that I don't fully understand what is happening at each stage of the process which is why I'm struggling to debug it. 我必须承认,我不完全了解过程的每个阶段都发生了什么,这就是为什么我要对其进行调试。

I am recommending carrierwave gem over paperclip. 我建议在回形针上使用载波宝石。 Easier to parse from link. 更容易从链接解析。

Carrierwave 载波

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM