簡體   English   中英

Rails 4將附件上傳的file_field添加到現有表單和控制器

[英]Rails 4 add file_field for attachment upload to existing form and controller

我是鐵桿的新手。 現在已經學習了幾個星期。 請原諒我的愚蠢。 我無法獲取我選擇上傳的文件。

我正在使用Rails 4.0.0。

我正在處理我的第一個應用程序,我開始遵循博客應用程序的rails指南。 我接受了它,並與它一起運行,並創建了一些不同的(錯誤跟蹤系統),只是試圖學習繩索。

所以,我有我的表格:

<%= form_for @post do |f| %>

我已經在我的file_field中添加了。 視圖中的顯示部分看起來並且在選擇文件時效果很好。

<%= f.label :attachment %>
<%= f.file_field :attachment %>

我已經從導軌4指南FYI中取出了這個。 所以我的控制器看起來像這樣:

class PostsController < ApplicationController

    def new
      @post = Post.new
    end

    def create
      @post = Post.new(params[:post].permit(:title, :text, :user, :screen))

      if @post.save
        redirect_to posts_path
      else
        render 'new'
      end
    end

    def show
      @post = Post.find(params[:id])
    end

    def index
      @posts = Post.all
    end

    def edit
      @post = Post.find(params[:id])
    end

    def update
      @post = Post.find(params[:id])

      if @post.update(params[:post].permit(:title, :text, :user, :screen))
        redirect_to posts_path
      else
        render 'edit'
      end
    end

    def destroy
      @post = Post.find(params[:id])
      @post.destroy
      redirect_to posts_path
    end

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

    private
    def post_params
      params.require(:post).permit(:title, :text, :user, :screen, :attachment)
    end

end

這里的新作品是上傳。 通過從數據庫中讀取和讀取並顯示,其他所有工作都正常。 當顯示視圖時,我創建文本條目,附加文件並點擊提交。 一切都寫入數據庫並顯示索引,但我試圖附加的文件沒有寫入〜/ bugs / public / uploads /

在此先感謝您的幫助。

我認為問題可能是:attachment屬性不是“創建”或“更新”操作中的允許參數。

編輯:我做簡單文件上傳的方式是使用Paperclip gem - 這個railscast很好地解釋了它。 它真的很容易使用。

還有這個答案可能會回答這個問題。

此外,使用強參數的標准方法是在私有方法中定義允許的參數並在控制器操作中調用該方法(因此您不必重復自己)。 這可能是錯誤的原因。

例:

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

希望有所幫助。

我有同樣的問題,

解決方案: -

刪除“def upload”並將代碼提供給“def create”本身

 > def create > > uploaded_io = params[:post][:attachment] > File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file| > file.write(uploaded_io.read) > end > > @post = Post.new(params[:post].permit(:title, :text, :user, :screen)) > > if @post.save > redirect_to posts_path > else > render 'new' > end > end 

確保“上傳”目錄存在於“公共”中。

您可以通過在文件操作之前添加此行來自動處理:

Dir.mkdir 'public/uploads' unless File.directory? 'public/uploads'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM