Search code examples
ruby-on-railsruby-on-rails-5

Rails 5.2.3 - Validation errors are displayed in console but are not passed to the view


When I submit a form with blank fields that are required I see the ROLLBACK and ActiveModel::Errors in the console but for some reason I can't render the errors in the view.

This is happening on both the new and edit templates. Needless to say, creating a new record or editing an existing one with the required fields works fine.

This is what my code looks like:

Model: transactions.rb

class Transaction < ApplicationRecord
  belongs_to :account
  belongs_to :category

  validates :date, :description, :amount, :category_id, :account_id, presence: true
end

Controller: transactions_controller.rb

 def new
    @transaction = Transaction.new
  end

  def create
    @transaction = Transaction.create(transaction_params)

    if @transaction.save
      redirect_to account_path(@account), notice: "Transaction created"
    else
      render :new
    end
  end

  def edit
    if @transaction.amount > 0
      @transaction_type = "income"
    else
      @transaction_type = "expense"
    end

    render :edit
  end

  def update
    if @transaction.update(transaction_params)
      redirect_to account_path(@account)
    else
      render :edit
    end
  end

  private
    def transaction_params
      params.require(:transaction).permit(:date, :description, :amount, :category_id, :account_id)
    end

View: new.html.erb (or edit.html.erb)

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

Log after submitting the form:

Started POST "/accounts/15/transactions" for 192.168.55.1 at 2019-09-07 03:00:24 +0000
Cannot render console from 192.168.55.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by TransactionsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"CJd+/rB6LcUqQAz0ZvY0cf8Dcu+2qzUYLCQHLWE2GElZtJrKbKq2EODFeVvKG6NkE2MxtIIjRreqHAnKu2sJ9A==", "transaction"=>{"date(1i)"=>"2019", "date(2i)"=>"9", "date(3i)"=>"7", "description"=>"", "category_id"=>"1", "amount"=>"0"}, "transaction_type"=>"Expense", "commit"=>"Add Transaction", "account_id"=>"15"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ /var/lib/gems/2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  Account Load (0.1ms)  SELECT  "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT $2  [["id", 15], ["LIMIT", 1]]
  ↳ app/controllers/transactions_controller.rb:64
   (0.1ms)  BEGIN
  ↳ app/controllers/transactions_controller.rb:24
  Category Load (0.2ms)  SELECT  "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/transactions_controller.rb:24
   (0.2ms)  ROLLBACK
  ↳ app/controllers/transactions_controller.rb:24
   (0.1ms)  BEGIN
  ↳ app/controllers/transactions_controller.rb:26
   (0.1ms)  ROLLBACK
  ↳ app/controllers/transactions_controller.rb:26
  Rendering transactions/new.html.erb within layouts/application

If I add p @transaction.errors in the create method or go into the Rails console and run @transaction.errors I do get the errors:

irb(main):026:0> @transaction.errors
=> #<ActiveModel::Errors:0x0000000006447158 @base=#<Transaction id: nil, date: nil, description: nil, amount: nil, account_id: nil, created_at: nil, updated_at: nil, category_id: 
nil>, @messages={:account=>["must exist", "can't be blank"], :category=>["must exist", "can't be blank"], :date=>["can't be blank"], :description=>["can't be blank"], :amount=>["can't be blank"]}, @details={:account=>[{:error=>:blank}, {:error=>:blank}], :category=>[{:error=>:blank}, {:error=>:blank}], :date=>[{:error=>:blank}], :description=>[{:error=>:blank}], :amount=>[{:error=>:blank}]}>

Something else I tried is adding these 2 lines to the new.html.erb:

<%= @transaction.errors %> renders: #<ActiveModel::Errors:0x00007ff650570500>

<%= @transaction.errors.full_messages %> renders: []


Solution

  • Processing by TransactionsController#create as JS, your form is being submitted using ajax, you need to render a js view or use a non-ajax request. Are you using form_with for your form? form_with defaults to remote forms, use form_for instead or update the view using a js response.