0

午後はみんな、

新しいファイルのアップロードの作成を処理するコントローラーがあります (これはタスクなので、ペーパークリップを使用できず、データベースに保存されているため、これらすべての欠点を知っており、不平を言うのを聞くことができます 笑) ただし、検証時にファイルの保存が失敗する (つまり、何もアップロードしようとしない) ため、新しいアップロード フォームへのリダイレクトは何もしていないようで、インデックス ページをレンダリングしようとします。renders、redirect_to(:back) などを使用してリダイレクトのさまざまなバリエーションを試しましたが、実際には何もしていないようです。

誰かに何かアイデアがあれば、それは大歓迎です。

コードはこちらです。

コントローラ

def create
    beginning = Time.now
    return if params[:attachment].blank?

    @attachment = Attachment.new
    @attachment.uploaded_file = params[:attachment]
    @time = (Time.now - beginning)
    if @attachment.save
      flash[:success] = "File uploaded in #{@time} seconds"
      redirect_to @attachment
    else
      flash[:notice] = "something went wrong"
      redirect_to 'new
    end
 end

モデル

class Attachment < ActiveRecord::Base
  has_many :anagrams, dependent: :destroy
  attr_accessible :filename, :content_type, :data
  validates_presence_of :filename, :data, :content_type

  def uploaded_file=(incoming_file)
    self.filename = incoming_file.original_filename
    self.content_type = incoming_file.content_type
    self.data = incoming_file.read
  end

  def filename=(new_filename)
    write_attribute("filename", sanitize_filename(new_filename))
  end

  private

  def sanitize_filename(filename)
    just_filename = File.basename(filename)
    just_filename.gsub(/[^\w\.\-]/, '_')
  end
end

ルート.rb

 resources :attachments, only: [:create, :new]
  resources :anagrams, only: [:create, :new]


 root to: "attachments#new"

誰かがもっとコードを見る必要がある場合は、ただ叫んでください、どうもありがとう

4

2 に答える 2

1

'new'にredirect_toする代わりに、エラーを表示できるようにフォームを再度レンダリングする必要があります。例えば:

if @attachment.save
  flash[:success] = "File uploaded in #{@time} seconds"
  redirect_to @attachment
else
  flash.now[:notice] = "something went wrong"
  render :action => 'new
end

本当にリダイレクトする必要がある場合は、エラーをデバッグする必要があります。これにより、エラーをダンプできます。

puts @attachment.errors.inspect

汚れているように見えますが、問題をすぐに見つけることができます:D

于 2012-08-06T15:53:13.533 に答える
0

[:attachment].blank? 私はelseステートメントでやりたいことをしていましたが、フラッシュ通知を入れてそこに「新規」をレンダリングすることは考えていませんでした。切り替えて動作します。

 def create
   beginning = Time.now
   if params[:attachment].blank?
     flash[:error] = "Please upload a file"
     render 'new'
   else
    @attachment = Attachment.new
    @attachment.uploaded_file = params[:attachment]
    @time = (Time.now - beginning)
    if @attachment.save
      flash[:success] = "File uploaded in #{@time} seconds"
      redirect_to @attachment
   end
  end
end
于 2012-08-06T21:11:51.977 に答える