rock_n_rolla
rock_n_rolla

Reputation: 357

How to render out errors on forms using form_for with multiple nested models

I have a form here for adding new transactions. I understand that the below is a little bit messy with all the nested resources, but it works for now whilst I'm still learning 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 %>

I have the following check in my transactions_controller.rb which works perfectly. If the condition is true, the script stops running and I am successfully redirected back to the new form. However, I cannot seem to get the error to display. To clarify: everything works as expected, except the rendering of the error message in the form above.

# 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

Would love some help on how to successfully render out errors to these forms with multiple nested models. Thank you!

Upvotes: 0

Views: 22

Answers (1)

Pavan
Pavan

Reputation: 33542

You have redirect_to new_company_captable_event_transaction_path which initializes a new request to the server, so the form errors are lost. You should use render instead of 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

Upvotes: 3

Related Questions