如何使用带有多个嵌套模型的form_for呈现表单上的错误

时间:2018-10-16 09:52:19

标签: ruby-on-rails

我这里有一个用于添加新交易的表格。我了解以下内容与所有嵌套资源有些混乱,但是当我仍在学习Rails时,它现在可以使用。

<%= form_for([@company, @captable, @event, @transaction]) do |f| %>
  <% if @transaction.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@transaction.errors.count, "error") %> prohibited this transaction from being saved:</h2>

      <ul>
      <% @transaction.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

我在transactions_controller.rb中进行了以下检查,效果很好。如果条件为true,则脚本停止运行,并且我已成功重定向到新表单。但是,我似乎无法显示该错误。需要说明的是:一切都按预期工作,除了上面表格中错误消息的呈现。

# Verify that the transaction is valid first before saving 
@selling_shareholder = Shareholder.find(params[:selling_shareholder_id])
if @transaction.number_of_stocks > @selling_shareholder.number_of_stocks #Seller cannot sell more stocks then they own 
    @transaction.errors.add(:number_of_stocks, "Seller cannot sell more stocks then they own")
    redirect_to new_company_captable_event_transaction_path
    return
end

在如何使用多个嵌套模型成功将错误呈现给这些表单方面,我们将提供一些帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

您有redirect_to new_company_captable_event_transaction_path可以初始化对服务器的新请求,因此会丢失表格错误。您应该使用render而不是redirect_to

# Verify that the transaction is valid first before saving 
@selling_shareholder = Shareholder.find(params[:selling_shareholder_id])
if @transaction.number_of_stocks > @selling_shareholder.number_of_stocks #Seller cannot sell more stocks then they own 
  @transaction.errors.add(:number_of_stocks, "Seller cannot sell more stocks then they own")
  render 'new'
end