如何使用Paperclip和Image Picker on Rails 4上的options_for_select保存图像?

我正在尝试通过一个表单来保存图像,该表单填充了一个带有多个选项的“选择”字段。 当用户单击选定图像时,选择表单使用图像选择器更改选项。 提交表单后,应使用Paperclip gem保存所选图像。

我想我只需要将所选选项中的图像URL指向一个将在Paperclip中打开它的方法,但我不太清楚如何做到这一点。 我是Rails的新手,谦虚地欣赏任何能指引我正确方向的东西!

这就是我所拥有的:

_form.html.erb

 v ] } )) %> 

如果我使用“:medium”,就像我通常在设置表单输入时所做的那样,我得到一个错误,上面写着“ActiveRecord :: AssociationTypeMismatch at / stories Medium(#70334728193840)”,得到字符串(#70334669736760)“,所以我尝试使用“:medium_id”,它显示所选选项的值而不是url。

使用“:medium_id”允许其余的表单字段正确保存而不会出现错误,但只保存图像的选项值,而不是图像本身。

story.rb

 class Story < ActiveRecord::Base belongs_to :medium accepts_nested_attributes_for :medium 

stories_controller.rb

 class StoriesController  [], medium_attributes: [:medium, :image], ) 

medium.rb

 require "open-uri" class Medium < ActiveRecord::Base has_one :story before_save :image_from_select def image_from_select(url) self.image = open(url) end end 

media_controller.rb

 def create @medium = Medium.new(medium_params) respond_to do |format| if @medium.save format.html { redirect_to @medium, notice: 'Medium was successfully created.' } format.json { render action: 'show', status: :created, location: @medium } else format.html { render action: 'new' } format.json { render json: @medium.errors, status: :unprocessable_entity } end end end private def set_medium @medium = Medium.find(params[:id]) end def medium_params params.require[:medium].permit(:image) end 

结束

schema.rb

 create_table "stories", force: true do |t| t.integer "medium_id" end create_table "media", force: true do |t| t.datetime "created_at" t.datetime "updated_at" t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.integer "story_id" end 

我试过引用以下内容但没有成功:

通过paperclip从URL保存图像 哪种方法是使用Paperclip在rails 4上从外部URL上传图像? http://runnable.com/UnsMH7fYN2V6AAAT/how-to-save-images-by-url-with-paperclip-for-ruby-on-rails-and-upload https://github.com/thoughtbot/paperclip/wiki /附件下载的,从-A-URL

提前致谢。