我不明白为什么表单没有经过验证。即使文本字段中没有值,执行create方法也是我使用的代码
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
模型
class Movie < ActiveRecord::Base
attr_accessible :title, :year
validates_presence_of :title
validates_presence_of :year
end
这是视图
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 !@movies.blank? %>
<% for item in @movies %>
<%= item.id %> <%= item.title %> (<%= item.year %>) <br />
<% end %>
<% else %>
<% end %>
答案 0 :(得分:1)
在控制器
中 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
在查看中,在验证失败时添加错误显示消息
<%= 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 !@movies.blank? %>
<% for item in @movies %>
<%= item.id %> <%= item.title %> (<%= item.year %>) <br />
<% end %>
<% else %>
No Movies found.
<% end %>
答案 1 :(得分:0)
调用@ movie.save时会进行验证。因为@movie无效,所以#save将返回false并且将填充@ movie.errors。
此验证不会阻止提交表单(并且#create正在执行)。为此,您希望使用JavaScript / jQuery和Rails查看验证。