我一直在关注本教程,将文件上传到db Rails File Upload
当文件保存并且我使用file_contents
上传文件时,问题是nested_attributes
字段为空。
subject.rb // model
class Subject < ApplicationRecord
has_many :documents
accepts_nested_attributes_for :documents
end
document.rb // model
class Document < ApplicationRecord
belongs_to :subject
def initialize(params = {})
@file = params.delete(:file)
super
if @file
self.filename = sanitize_filename(@file.original_filename)
self.content_type = @file.content_type
self.file_contents = @file.read
end
end
private
def sanitize_filename(filename)
return File.basename(filename)
end
end
_form.html.erb //查看
<%= form_for(subject) do |f| %>
.......
<div class="uk-form-row">
<%= f.fields_for :documents do |d| %>
<%= d.file_field :file, class:"uk-width-1-1 uk-form-large", placeholder:"upload document" %>
<% end %>
</div>
............
<% end %>
subjects_controller.rb
def new
@subject = Subject.new
@subject.documents.build
end
def create
@subject = Subject.new(subject_params)
respond_to do |format|
if @subject.save
format.html { redirect_to @subject, notice: 'Lesson was successfully created.' }
else
format.html { render :new }
end
end
end
private
def subject_params
params.require(:subject).permit(:title, documents_attributes:[:file])
end
我是以正确的方式吗?我错过了什么?我需要你的想法。
谢谢,