dorofr
dorofr

Reputation: 25

Rails form validaiton issues

I don't get why the form is not validated. create method is executed even if there are no values in the text fields here is the code that I use

class MoviesController < ApplicationController
  def new 
    @movie = Movie.new
    @movies = Movie.find(:all)
  end

  def create
    @movie = Movie.new(params[:movie])
    if @movie.save
      redirect_to "http://localhost:3000/movies/new/"
    end
  end
end

Model

class Movie < ActiveRecord::Base
  attr_accessible :title, :year

  validates_presence_of :title
  validates_presence_of :year

end

Here is the view

Enter new movie information 
<%= form_for @movie do |f|%><br />
    Title <%= f.text_field :title %><br />
    Year <%= f.text_field :year %><br />
    <%= f.submit %>
<% end %>

<hr />
List of all movies<br />
<% if [email protected]? %>
  <% for item in @movies %>
    <%= item.id %>&nbsp;<%=  item.title %> (<%= item.year %>) <br />
  <% end %>
<% else %>

<% end %>

Upvotes: 0

Views: 246

Answers (2)

Pritesh Jain
Pritesh Jain

Reputation: 9146

In Controller

  def create
    @movie = Movie.new(params[:movie])
    if @movie.save
      redirect_to new_movie_path  # You sure you what to redirect this to new after success? 
                                  # redirect as per your project requirement on success
    else
      render :new # render new with errors displayed
    end
  end

In View added error display message when validation fails

<%= form_for @movie do |f|%>
  <% if @movie.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@movie.errors.count, "error") %> prohibited this from being saved:</h2>
        <ul>
        <% @movie.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
    <br />
    Title <%= f.text_field :title %><br />
    Year <%= f.text_field :year %><br />
    <%= f.submit %>
<% end %>

<hr />
List of all movies<br />
<% if [email protected]? %>
  <% for item in @movies %>
    <%= item.id %>&nbsp;<%=  item.title %> (<%= item.year %>) <br />
  <% end %>
 <% else %>
   No Movies found.
<% end %>

Upvotes: 1

Ian Fleeton
Ian Fleeton

Reputation: 1157

The validation occurs when you call @movie.save. Because @movie is not valid, #save will return false and @movie.errors will be populated.

This validation does not prevent the form being submitted (and #create being executed). For that you want to look at validations with JavaScript/jQuery and Rails.

Upvotes: 0

Related Questions