Search code examples
ruby-on-railsrubyruby-on-rails-5simple-form

Validation error messages not showing in form view


I have a simple model :

class Property < ApplicationRecord
 belongs_to :user
 has_many :invoices, dependent: :destroy
 has_many :tenants, dependent: :destroy

 validates :street, presence: true, length: { maximum: 50}
 validates :city, presence: true, length: { maximum: 50}
 validates :zip, presence: true, length: { maximum: 10}
 validates :rent, presence: true, length: { maximum: 50}


 def receivable
  (self.rent.to_i + self.charges.to_i)
  end
end

When trying in the console, the validation errors come as expected:

[2] pry(main)> prop = Property.new(street:"zzz")
 => #<Property:0x007fb99cde1cc0 id: nil, number: nil, streetype: nil, street: 
 "zzz", city: nil, zip: nil, rent: nil, charges: nil, user_id: nil, created_at: 
 nil, updated_at: nil>

[3] pry(main)> prop.save
(0.3ms)  BEGIN
(0.8ms)  ROLLBACK
=> false

[4] pry(main)> prop.errors.full_messages
=> ["User must exist", "City can't be blank", "Zip can't be blank", "Rent can't 
be blank"]

Here is the controller:

def new
 @user =  current_user
 @property = @user.properties.build
end

def create
 @user =  current_user
 @property = @user.properties.create(property_params)
 @property.user_id = current_user.id
  if @property.save
   flash[:notice] = "Nouveau Bien créé !"
   redirect_to user_properties_path
  else
   redirect_to new_user_property_path
 end
end

And here is the form view:

<div class="container center">
 <div class="row white">
  <div">
   <h2>Nouveau bien</h2>
   <%= simple_form_for([@user, @property]) do |j| %>
    <%= j.input :number, label:"Numéro" %>
    <%= j.input :streetype, label: "Laisser vide si nécessaire", collection: [" 
    ","rue","boulevard","allée"] , prompt: "Choisir" %>
    <%= j.input :street, label:"Nom" %>
    <%= j.input :city, label:"Commune / Ville" %>
    <%= j.input :zip, label:"Code Postal" %>
    <%= j.input :rent, label:"Montant du Loyer" %>
    <%= j.input :charges, label:"Montant des charges" %>
    <br>
    <%= j.submit 'Créer', class: "form-control btn btn-info" %>
   <% end %>
  </div>
 </div>
</div>

When omitting one of the fields on purpose, the controller redirect to the correct form viw but validation error messages are not present. They use to show up but they disapeared for some reason.

Any idea why?

Thank you!


Solution

  • instead of redirect_to new_user_property_path in else block, you should

    render 'new'
    

    Reason: redirect instructs the browser to make the new request, because of which you end up loosing the context of @property object with it's errors. It actually makes a fresh request to new action. render will continue with the current action (which is create in this case) and render the response in new view with @property, errors and previous form body.