我有我已經制作了一個虛擬測試站點來驗證的代碼。這段代碼在使用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