预先填充file_field的解决方法?

时间:2016-11-04 12:21:55

标签: ruby-on-rails ruby parameters

我认为你不能预先填充file_field,所以我一直在努力解决同一个目标,即通过用户A获取已经上传到应用程序的图像然后让用户B能够保存与他自己相同的图像,类似于pinterest。

这是我尝试过的:

索引

<%= link_to new_inspiration_path(inspiration_image: inspiration.image) %>

控制器

def new
  @inspiration = current_user.inspirations.build
  @inspiration.image = URI.parse(params[:inspiration_image])
end

服务器

Started GET "/inspirations/new?inspiration_image=%2Fsystem%2Finspirations%2Fimages%2F000%2F000%2F069%2Foriginal%2Frule_1.jpg%3F1478260961" for 127.0.0.1 at 2016-11-04 08:10:41 -0400
Processing by InspirationsController#new as */*
  Parameters: {"inspiration_image"=>"/system/inspirations/images/000/000/069/original/rule_1.jpg?1478260961"} # For example, this is the image url I'm trying to duplicate for User B
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 129]]
  Inspiration Load (0.4ms)  SELECT  "inspirations".* FROM "inspirations" WHERE "inspirations"."id" IS NULL LIMIT 1
Completed 400 Bad Request in 6ms

_form

<%= simple_form_for(@inspiration, html: { data: { modal: true } }) do |f| %> 
  <%= image_tag @inspiration.image.url if @inspiration.image.present? %> # I get error: ActionController::ParameterMissing (param is missing or the value is empty: inspiration):
  <%= f.file_field :image %>
<% end %>

模型

class Inspiration < ActiveRecord::Base
  has_attached_file :image, :styles => { :medium => "300x300>", :small => "150x150>" }
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
  belongs_to :user

  def image_remote_url=(url_value)
    self.image = URI.parse(url_value).to_s unless url_value.blank?
    super
  end
end

1 个答案:

答案 0 :(得分:1)

// explicit val s: String = a.value // implicit conversion (although typically frowned-upon as bad practice) implicit def unwrapA(a: A): String = a.value val s: String = a 作业更改为@inspiration.image

可以在此处找到更多信息:https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL

修改 根据链接中的信息更改模型:

@inspiration.image = URI.parse(params[:inspiration_image])

attr_reader :image_remote_url

删除@image_remote_url = url_value电话

将作业更改为super