开发者

How to upload an image with other form inputs via ruby on rails?

开发者 https://www.devze.com 2023-03-31 19:09 出处:网络
I was wondering how to implement an image upload using ruby on rails v3? What I got so far is the image is uploaded to my public/uploads directory but in the database the hashed value from the form is

I was wondering how to implement an image upload using ruby on rails v3? What I got so far is the image is uploaded to my public/uploads directory but in the database the hashed value from the form is stored.

EX of hashed value:

!ruby/object:ActionDispatch::Http::UploadedFile 
content_type: image/jpeg
headers: |
  Content-Disposition: form-data; name="farmer[picture]"; filename="picture.JPG"
  Content-Type: image/jpeg

original_filename: picture.JPG
tempfile: !ruby/object:File {}

Controller:

def new
    @farmer = Farmer.new
  end

  def create
    @farmer = Farmer.new(params[:farmer])
    if @farmer.save
      uploaded_io = params[:farmer][:picture]
      File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
        file.write(uploaded_io.read)
      end
      flash[:success] = "#{@farmer.firstName} #{@farmer.lastName} added"
      redirect_to @farmer
    else
      redirect_to new_path
    end
  end

Model: empty

View:

<%= form_for(@farmer, :html => { :multipart => true }) do |f| %>
  <div class="field">
    <%= f.label :picture, "Picture" %>
    <%= f.file_field :picture %>
  </div>
  <div class="actions">
    <%= f.submit "Post"%>
  </div>
<% end %>开发者_如何学C

So what I would like help with is how to store uploads/image.JPG into the database not the hashed value?


Try not to invent bicycle , paperclip gem is what you are looking for, you may found also alternatives at: ruby toolbox

Cheers


Carrierwave is the best for your problem. If you are using peperclip, you may try to replace with carrierwave. if you have any problem, let me know

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号