我有我已经制作了一个虚拟测试站点来验证的代码。这段代码在使用Rails(4.2.5.1)时完全按照预期工作,但在使用Rails(5.0)时失败。我不明白实际问题在哪里。Carrierwave上传工作在Rails 4.x中,但不是Rails 5
我的具体错误是Attachment article must exist
,它告诉我以某种方式我没有通过一个文章实例,但我只是不明白为什么这个工程,就像在一个Rails 4.x实例,但不是在一个Rails 5测试版,它的数字一定是我在别处没见过的东西。希望有人知道。
我有一个附件型号:
class Attachment < ApplicationRecord
belongs_to :article
mount_uploader :file, AttachmentUploader
end
我有一篇文章型号:
class Article < ApplicationRecord
has_many :attachments, dependent: :destroy
accepts_nested_attributes_for :attachments, reject_if: :all_blank
end
我有一个文章控制器:
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
# GET /articles/new
def new
@article = Article.new
@article.attachments.build
end
def create
@article = Article.new(article_params)
respond_to do |format|
if @article.save
format.html { redirect_to @article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: @article }
else
format.html { render :new }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
@article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:name, :content, attachments_attributes: [:file, :file_cache])
end
end
我的形式,你会期望。我的文章形式:
<%= form_for(article) do |f| %>
<% if article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% article.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content %>
</div>
<div id="attachments">
<h3>Attachments</h3>
<%= render partial: "attachments/form", locals: { f: f, index: 0 } %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的附件部分:
<%= f.fields_for :attachments, child_index: index do |ff| %>
<%= ff.file_field :file, as: :file, label: "File ##{index += 1}" %>
<%= ff.hidden_field :file_cache %>
<% end %>
刚刚尝试过。同样的问题。我也曾尝试过这一点:)。 – Art
请发布完整的stacktrace。 – Dharam
这不是错误,我可以访问跟踪。这是一个很好的清理错误,显示我需要分配一篇文章。 1错误禁止保存此文章: 附件文章必须存在 如果我可以从处理的错误中获得堆栈跟踪,我不知道如何。 – Art