以下のように、Paperclip によって処理されるアタッチメントを持つstory
モデルをセットアップしました。image
class Story < ActiveRecord::Base
has_attached_file :image # [...]
attr_accessible :user_id, :title, :image, :image_file_name
belongs_to: user
validates_presence_of :user_id
validates :title, :length => { :maximum => 50 }
validates_attachment_size :image, :less_than => 2.megabytes, :unless => Proc.new { |story| story[:image].nil? }
# [...]
end
ストーリー フォームに入力すると、次のようになります。
<%= form_for @story, html: { multipart: true } do |f| %>
<% if @story.errors.any? %>
<div id="error-explanation">
<ul>
<% @story.errors.full_messages.each do |msg| %>
<li class="error-mess">Error: <%= msg.downcase %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :title %></td>
<%= f.file_field :image %>
<%= f.submit t('.send') %>
<% end %>
story.title が長すぎるために検証が失敗した場合、適切なエラー メッセージと無効なタイトルが既に入力された状態でフォームが正しく再表示されますが、file_field
現在は空白であり、ファイルを再選択するためにもう一度クリックする必要があります。アップロードしたい。
そして、これが私のstories_controller.rbの外観です。
def create
@story = @current_user.stories.new(params[:story])
if @story.save
redirect_to thanks_path
else
# !@story.save so I render action 'new' again just to
# bang my head against this 'anomaly'
render action: "new"
end
end
検証エラーの後、ユーザーがアップロードするファイルを再選択する必要がないようにするにはどうすればよいですか?