Ruby-on-rails-rails-file-uploading
Ruby on Rails-ファイルのアップロード
サイト訪問者がサーバーにファイルをアップロードする必要がある場合があります。 Railsでは、この要件を非常に簡単に処理できます。 次に、シンプルで小さなRailsプロジェクトを進めます。
いつものように、 testfile という新しいRailsアプリケーションから始めましょう。 単純なrailsコマンドを使用して、アプリケーションの基本構造を作成しましょう。
tp> rails new testfile
アプリケーション開発を開始する前に、以下に示すようにgemファイルをインストールする必要があります-
gem install carrierwave
gem install bootstrap-sass
あなたのgemfileを開き、次の図に示すように、下部に次の2つのgemを追加します-
gemファイルにgemを追加した後、コンソールで次のコマンドを実行する必要があります-
bundle install
モデルの作成
以下に示すように、名前と添付ファイルとして2つの文字列を持つモデルを作成する必要があります-
rails g model Resume name:string attachment:string
以下に示すように、データベースの移行を作成する必要があります-
rake db:migrate
次のようにコントローラーを生成する必要があります-
rails g controller Resumes index new create destroy
すばらしいです! これで、基本構造が設定されました。 次に、アップローダーを作成する必要があります。 Uploaderは、carrierwave gemから来て、carrierwaveにファイルの処理方法を指示します。 つまり、すべてのファイル処理機能が含まれていました。 以下に示すように、コマンドを実行してアップローダーを作成します
rails g uploader attachment
次に、履歴書モデルを開き、以下に示すようにアップローダーを呼び出します。 再開モデルはapp/models/resume.rbに配置されました-
class Resume < ActiveRecord::Base
mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model.
validates :name, presence: true # Make sure the owner's name is present.
end
コントローラで作業する前に、以下に示すようにconfig/routes.dbを変更する必要があります-
CarrierWaveExample::Application.routes.draw do
resources :resumes, only: [:index, :new, :create, :destroy]
root "resumes#index"
end
以下に示すようにコントローラーを編集します。
class ResumesController < ApplicationController
def index
@resumes = Resume.all
end
def new
@resume = Resume.new
end
def create
@resume = Resume.new(resume_params)
if @resume.save
redirect_to resumes_path, notice: "The resume #{@resume.name} has been uploaded."
else
render "new"
end
end
def destroy
@resume = Resume.find(params[:id])
@resume.destroy
redirect_to resumes_path, notice: "The resume #{@resume.name} has been deleted."
end
private
def resume_params
params.require(:resume).permit(:name, :attachment)
end
end
app/assets/stylesheets/resumes.css.scssにあるcss file.cssファイルにブートストラップ実装を追加しましょう
@import "bootstrap";
ここでapp/views/layouts/application.erbを開き、以下に示すようにコードを追加します-
<!DOCTYPE html>
<html>
<head>
<title>finddevguides</title>
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class = "container" style = "padding-top:20px;">
<%= yield %>
</div>
</body>
</html>
次に、以下に示すようにインデックスビューを設定する必要があります-
<% if !flash[:notice].blank? %>
<div class = "alert alert-info">
<%= flash[:notice] %>
</div>
<% end %>
<br/>
<%= link_to "New Resume", new_resume_path, class: "btn btn-primary" %>
<br/>
<br/>
<table class = "table table-bordered table-striped">
<thead>.
<tr>
<th>Name</th>
<th>Download Link</th>
<th> </th>
</tr>
</thead>
<tbody>
<% @resumes.each do |resume| %>
<tr>
<td><%= resume.name %></td>
<td><%= link_to "Download Resume", resume.attachment_url %></td>
<td><%= button_to "Delete", resume, method: :delete, class: "btn btn-danger", confirm: "Are you sure that you wish to delete #{resume.name}?" %></td>
</tr>
<% end %>
</tbody>
</table>
では、newl.erbを編集してフォームコードを追加しましょう。
<% if [email protected]? %>
<div class = "alert alert-error">
<ul>
<% @resume.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class = "well">
<%= form_for @resume, html: { multipart: true } do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :attachment %>
<%= f.file_field :attachment %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
</div>
サーバーを起動して、http://localhost:3000にアクセスします。 次のような画面が生成されます-
最後に、許可されているファイルタイプのリストをフィルタリングする必要があります。 そのためには、以下に示すようにapp/uploaders/attachment_uploader.rbに簡単なコードを追加する必要があります
class AttachmentUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(pdf doc htm html docx)
end
end
サーバーを起動して、http://localhost:3000にアクセスします。 間違った形式を入力してください。以下に示すように、間違ったメッセージを生成します-
*File* オブジェクトの詳細については、* Rubyリファレンスマニュアル*をご覧ください。