没有任何gemfile Rails4上传图片

时间:2014-07-24 20:55:37

标签: ruby-on-rails-4

我是Ruby on Rails的新手。 我试图上传没有任何gemfile的图像。我正在关注http://guides.rubyonrails.org/form_helpers

这是我的books_controller.rb文件:

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]


  def index
    @books = Book.all
  end


  def show
  end


  def new
    @book = Book.new
  end


  def edit
  end

  def create
    @book = Book.new(book_params)

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
        format.json { render action: 'show', status: :created, location: @book }
      else
        format.html { render action: 'new' }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end


  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end


  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url }
      format.json { head :no_content }
    end
  end

  def upload
    uploaded_io = params[:book][:image_url]
    File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
      file.write(uploaded_io.read)
    end
  end

  private

    def set_book
      @book = Book.find(params[:id])
    end


    def book_params
      params.require(:book).permit(:title, :description, :image_url)
    end
end

这是我的form.html.erb文件:

<%= form_for @book do |f| %>
  <% if @book.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@book.errors.count, "error") %> prohibited this book from being saved:</h2>

      <ul>
      <% @book.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.label :image_url %><br>
    <%= f.file_field :image_url %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

这是我的schema.rb文件:

ActiveRecord::Schema.define(version: 20140724173638) do

  create_table "books", force: true do |t|
    t.string   "title"
    t.text     "description"
    t.string   "image_url"
    t.datetime "created_at"
    t.datetime "updated_at"
  end
end

我还创建了一个目录(公共/上传)。 但它没有工作。当我提交“创建按钮”显示这样的事情: TypeError:无法将ActionDispatch :: Http :: UploadedFile强制转换为字符串:INSERT INTO“books”(“created_at”,“description”,“image_url”,“title”,“updated_at”)VALUES(?,? ,?,?,?,?,?)

有什么不对?

谢谢, Mezbah

0 个答案:

没有答案