在rails 5.2.3
应用程序中,我有一个模型Post
,该模型使用active_storage附加文件,并具有duration
和place
的字段。 duration
必须存在。
class Post
has_one_attached :video
validates :duration, presence: true
end
使用simple_form
表单中的字段声明为
<%= f.input :duration %>
<%= f.input :place %>
<%= f.input :video %>
控制器具有以下用于创建的逻辑
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = 'Post has been saved'
redirect_to root_path
else
@title = 'New Post'
@user = current_user
render :new
end
end
private
def post_params
params.require(:post).permit(:duration, :video)
end
如果验证失败,则表单显示place
的值,但是我丢失了视频的文件名。这意味着用户必须再次选择文件。我该如何解决?
根据Thanh的建议,我确实检查了此SO问题,并尝试将simple_form字段更改为
<%= f.hidden_field :video, value: f.object.image.signed_id if f.object.video.attached? %>
<%= f.file_field :video %>
这记住了文件名,但没有显示它。所以我做了以下工作:
<% if f.object.video.attached? %>
<span><strong>Video File Name:</strong> <%= f.object.video.blob.filename.to_s %>. To change, choose different file below:</span>
<% end %>
<%= f.hidden_field :video, value: f.object.image.signed_id if f.object.video.attached? %>
<%= f.file_field :video %>