当控制器验证失败时如何记住active_storage文件名

问题描述 投票:0回答:1

rails 5.2.3应用程序中,我有一个模型Post,该模型使用active_storage附加文件,并具有durationplace的字段。 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的值,但是我丢失了视频的文件名。这意味着用户必须再次选择文件。我该如何解决?

ruby-on-rails ruby-on-rails-5 simple-form rails-activestorage
1个回答
0
投票

根据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 %>
© www.soinside.com 2019 - 2024. All rights reserved.