Jbur43
Jbur43

Reputation: 1312

Errors within form not displaying in view

I am trying to display errors in my view when a form is not submitted correctly. I have a validation set in my model for location to be present and in my form I am using the errors method to try and display the errors in my view. Below is my code. The validation is working, because I get a rails error when location is nil, it's just not displaying the msg as html.

model

class Destination < ActiveRecord::Base
    validates :location, presence: true
end

form new.html.erb

<%= form_for @destination do |f| %>
    <% if @destination.errors.any? %>   
            <% @destination.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
    <% end %>

    <%= f.label :location %>
    <%= f.text_field :location %><br>
    <%= f.submit %>
<% end %>

controller

def create
        @destination = Destination.new(destination_params)

        if @destination.save!
            redirect_to destinations_path
        else
            render new_path
        end
    end

    private

    def destination_params
        params.require(:destination).permit(:location, :description)
    end
end

Upvotes: 0

Views: 41

Answers (3)

Radix
Radix

Reputation: 2767

@destination.save! will throw an error. You have to do something like;

if @destination.save # returns true if successfully saved else false
  redirect_to destinations_path
else
  flash[:errors] = @destination.error_messages # Display errors in view
  render new_path
end

HTH.

Upvotes: 0

Pitabas Prathal
Pitabas Prathal

Reputation: 1012

@destination.save! will raise an error if not successful.

@destination.save will return true or false.

Upvotes: 1

Yaro
Yaro

Reputation: 568

@destination.save! will throw error in case of unsuccessful saving. To get to the render new_path line you have to do just @destination.save.

Upvotes: 1

Related Questions