【问题标题】:When I do user.file.attach(params[:file]) it doesn't save when using active storage当我执行 user.file.attach(params[:file]) 时,使用活动存储时它不会保存
【发布时间】:2019-11-06 15:00:23
【问题描述】:

@user.file.attach(params[:file]): 行出现此错误:

ActiveRecord::RecordNotSaved 在 UsersController#runFile 中。 未能保存新关联的 file_attachment。

我正在使用活动存储来存储文件。

在我的用户模型中,我有这个代码:

has_one_attached :file

在我的用户控制器中, 我有这个代码:

def runFile 
```
  @user.file.attach(params[:file])
```
end

```
def user_params
    params.require(:user).permit(:file)
end

在我的视图中我有这个代码:

<%= form_with(model: user, local: true) do |form| %>
  <% if user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(user.errors.count, "error") %> prohibited 
              this user from being saved:</h2>

     <ul>
      <% user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

   <div class="field">
     <%= form.label :file %>
    <%= form.file_field :file %>
  </div>
 <br> 

  <h6 class="actions">
    <%= form.submit "Create" %>
  </h6> 
<% end %>

这是我为每个用户单击运行文件的 runFile 方法的显示表单:

<p id="notice"><%= notice %></p>
    <%= link_to "Run File", runFile_path, method: :post %>


<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

【问题讨论】:

  • 我在runFile方法中也有@user.save

标签: ruby-on-rails ruby model-view-controller rubygems rails-activestorage


【解决方案1】:

我认为你混合了一些东西。

要显示表单,您需要一个普通链接(不带method)。在您的情况下,它将是runFile。但是,runFile 只负责显示表单。您需要另一种方法来处理提交表单的操作。类似于editupdate 方法。

以下是它的外观:

def runFile_form
  # do whatever you need to display the form
end

def runFile
  @user.file.attach(params[:file])
end

def user_params
  params.require(:user).permit(:file)
end

在路由中,请为runFile_form方法定义一个GET路由并在显示页面上使用:

<%= link_to "Run file", runFile_form_path %>

【讨论】:

  • 现在出现了一个新错误——我猜可能 :file 是空的,所以我在视图中所做的是否有问题
  • @sr1 你能用整个表格的代码更新你的问题吗?
  • runFile_form 方法会调用 runFile 吗?如果不是,它会在哪里调用?这也能解决新关联的 file_attachment 不保存的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2011-07-17
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多