关于这个有很多问题,但似乎都没有帮助。是的,我看过this rails cast .
我有一个作者,他有很多书,像这样:
作者:
class Author < ActiveRecord::Base
attr_accessible :name
has_many :books, dependent: :destroy
accepts_nested_attributes_for :books, allow_destroy: true
validates :name, presence: true
validates :name, length: { minimum: 3 }
end
书:
class Book < ActiveRecord::Base
attr_accessible :name, :year
belongs_to :author
validates :name, :year, presence: true
validates :year, numericality: { only_integer: true, less_than_or_equal_to: Time.now.year }
end
我创建了以下表单以在 authors#show 中向作者添加一本书:
<%= form_for([@author, @book], html: { class: "well" }) do |f| %>
<% if @book.errors.any? %>
<div class="alert alert-block">
<ul>
<% @author.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
#labels and buttons...
<% end %>
...使用以下 authors_controller 方法:
def show
@author = Author.find(params[:id])
@book = @author.books.build
end
...以及以下 books_controller 方法:
def create
@author = Author.find(params[:author_id])
if @author.books.create(params[:book])
redirect_to author_path(@author)
else
render action: :show
end
end
我似乎无法弄清楚为什么表单不显示任何错误消息。我遵循了 railscasts 的例子,他们说应该有一个 books 的实例变量而不是 @author.books.build,所以我把后者放在 Controller 中,@book 放在表单中 - 仍然无济于事。
感谢您的帮助!
最佳答案
让我们逐步了解它。
您提交创建,然后进入您的创建操作
def create
@author = Author.find(params[:author_id])
if @author.books.create(params[:book])
redirect_to author_path(@author)
else
render action: :show
end
end
(旁注,如果找不到@author 怎么办。您没有处理这种情况。)
现在,作者找到了,但是 @author.books.create 失败了(返回 false),所以你渲染了 show Action 。
这使用展示模板,但不调用展示操作代码。 (旁注,也许新页面会是更好的选择,因此用户可以尝试重新创建。)
此时@author 被实例化为您找到的作者,而不是@book。所以@book,如果被调用将为零。
您的节目模板可以
if @book.errors.any?
这不是真的,所以将跳过 if 中的模板的其余部分。这就是没有错误的原因。
您不需要 form_for 来显示错误消息。如果您切换到使用新模板,那么将有一个表单可以重试。
所以让我们切换到渲染新的。
Class BooksController < ApplicationController
def new
@author = Author.find(params[:author_id])
@book = @author.books.build
end
def create
@author = Author.find(params[:author_id])
@book = @author.books.build(params[:book])
if @author.save
redirect_to author_path(@author)
else
render action: :new
end
end
您的新模板将是
<% if @author.errors.any? %>
<div class="alert alert-block">
<ul>
<% @author.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% if @book.errors.any? %>
<div class="alert alert-block">
<ul>
<% @book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_for([@author, @book], html: { class: "well" }) do |f| %>
#labels and buttons...
<% end %>
关于ruby-on-rails - 嵌套模型验证 - 错误不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972112/