Rails 4 - 在数据库中保存图像

Luk*_*itz 3 ruby ruby-on-rails ruby-on-rails-4

亲爱的程序员你好,

我正在尝试使用电子书"Praxiswissen - Ruby on Rails"开发一个Web应用程序.我的问题是我想通过表单将图像保存到我的项目目录中.数据库只保存图片的名称,节省时间:

def unique_and_proper_filename(filename)
    Time.now.to_i.to_s + '_' + File.basename(filename)
end 
Run Code Online (Sandbox Code Playgroud)

我的问题是我的照片在提交表格后没有保存.我没有得到一些例外,这就是为什么我不知道我的问题在哪里.

控制器:

class PostsController < ApplicationController

  require 'will_paginate'

  def new
     @post = Post.new
  end

  # information about saving the picture
  def create
     @post = Post.new(params[:post].permit(:title, :description, :date, :image_file, :thumbnail_file))

     # Form isn't correctly filled message
     if !@post.valid?
        flash.now[:notice] = "Bitte f&uuml;llen Sie alle Felder aus und &uuml;berpr&uuml;fen Sie Ihre Angaben."
        render(:action => :new)

     # Files weren't saved message
     elsif !@post.save_files
        flash.now[:notice] = "Es trat ein Fehler beim Hochladen der Dateien auf."
        render(:action => :new)

     # Files saved correctly message
     else
        @post.save
        flash[:notice] = "Dateien wurden hochgeladen und die Daten wurden gespeichert."
        redirect_to(:action => :list)
     end
  end

  # list action for listing my pictures
  def list
    @posts = Post.paginate(:page => params[:page], :order => "date DESC", :per_page => 15)
    @post_pages = Post.paginate(:page => params[:page], :order => "date DESC", :per_page => 15)
  end

end
Run Code Online (Sandbox Code Playgroud)

HTML表格:

<h2>Neues Foto anlegen</h2>
<%= form_tag({:action => :create}, :multipart => true) %>
<h3>Bilddaten</h3>
<p>
    Titel<br/>
    <%= text_field(:post, :title) %>
</p>
<p>
    Beschreibungen<br/>
    <%= text_field(:post, :description) %>
</p>    
<p>
    Datum und Uhrzeit<br/>  
    <%= datetime_select(:post, :date, :order => [:day, :month, :year, :hour]) %>
</p>
<p>
    <h3>Datei-Upload</h3>   
    <p>
        Bilddatei:<br/>
        <%= file_field(:post, :image_file) %>
    </p>    
    <p>
        Thumbnail:<br/>
        <%= file_field(:post, :thumbnail_file) %>
    </p>
    <%= submit_tag("Speichern") %>
</p>
</form>
Run Code Online (Sandbox Code Playgroud)

模型:

class Post < ActiveRecord::Base

  validates_presence_of(:title, :description, :date, :image, :thumbnail)
  I18n.enforce_available_locales = false

  def image_file= (fileobj)
    if fileobj.size > 0
      @image_file = fileobj
      self.image = unique_and_proper_filename(fileobj.original_filename)
    end
  end

  def thumbnail_file= (fileobj)
    if fileobj.size > 0
      @thumbnail_file = fileobj
      self.thumbnail = unique_and_proper_filename(fileobj.original_filename)
    end
  end 

  def save_files

    # Bilddatei save
    if !save_uploaded_file(@image_file, IMAGE_DIR, self.image)
      return false
    end

    # Thumbnail save
    if !save_uploaded_file(@thumbnail_file, THUMBNAIL_DIR, self.thumbnail)
      return false
    end

  end

  private 
  def unique_and_proper_filename(filename)
    Time.now.to_i.to_s + "_" + File.basename(filename)
  end

  private 
  def save_uploaded_file(fileobj, filepath, filename)

    # Complete Path
    complete_path = Rails.root + "/public/" + filepath

    # if neccessary, create directory
    FileUtils.mkdir_p(complete_path) unless File.exists?(complete_path)

    # save data
    begin
      f = File.open(complete_path + "/" + filename, "wb")
      f.write(fileobj.read)
    rescue 
      return false
    ensure
      f.close unless f.nil?
    end

  end

end
Run Code Online (Sandbox Code Playgroud)

当我正确填写表单时,我只收到保存文件出错的消息,但它应该返回一条消息,说明我的文件已保存.

对于那么长的问题,我很抱歉,但我真的不知道我的问题在哪里......如果需要更多的信息或代码,我会尽快添加它.

非常感谢你提前!

Ric*_*eck 17

对不起,我只能推荐我们用的东西:


回形针

我很欣赏你正在使用的教程,但我强烈建议使用回形针宝石

这将为您处理所有繁重的工作:

#GemFile
gem "paperclip", "~> 4.1.1"
Run Code Online (Sandbox Code Playgroud)

模型

#app/models/post.rb
Class Post < ActiveRecord::Base
    has_attached_file :image
end

#migration
add_attachment :posts, :image
Run Code Online (Sandbox Code Playgroud)

调节器

#app/controllers/posts_controller.rb
def new
    @post = Post.new
end

def create
    @post = Post.new(post_params)
end

private

def post_params
     params.require(:post).permit(:image, :other, :params)
end
Run Code Online (Sandbox Code Playgroud)

视图

#app/views/posts/new.html.erb
<%= form_for @post do |f| %>
    <%= f.file_field :image %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 回形针很棒,我也推荐它作为制作一个合适的应用程序的方式,但是当学习时,要知道如何自己做一些事情而不仅仅是把它交给一个神奇的宝石来做它.我实际上认为"魔术"是Rails在学习如何使用它时遇到的最大问题. (11认同)
  • 是的,我正在使用教程..谢谢您的推荐!当然,我赞成你的回答,但我更愿意按照我的教程在我现有的代码中找到问题。如果没有更多答案可以帮助我解决我的代码,我会接受您的答案并尝试“回形针”。谢谢! (2认同)
  • 当然 - 我只是想突出你的选择:) (2认同)

Luk*_*itz 6

我很幸运地说我发现了我的问题。我save_files在我的方法Post模型不回来true..

我发布这个答案是因为也许有人可以用这个问题作为他自己问题的答案。这是我添加的地方return true

def save_files

    # Bilddatei save
    if !save_uploaded_file(@image_file, IMAGE_DIR, self.image)
      return false
    end

    # Thumbnail save
    if !save_uploaded_file(@thumbnail_file, THUMBNAIL_DIR, self.thumbnail)
      return false
    end

    return true   # <--------- Need to be added!

end
Run Code Online (Sandbox Code Playgroud)