0

我不明白为什么表格没有经过验证。即使文本字段中没有值,也会执行 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 %>&nbsp;<%=  item.title %> (<%= item.year %>) <br />
  <% end %>
<% else %>

<% end %>
4

2 回答 2

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 %>&nbsp;<%=  item.title %> (<%= item.year %>) <br />
  <% end %>
 <% else %>
   No Movies found.
<% end %>
于 2012-07-02T10:14:47.593 回答
0

当您调用@movie.save 时会进行验证。因为@movie 无效,所以#save 将返回false 并填充@movie.errors。

此验证不会阻止提交表单(并执行#create)。为此,您想查看使用 JavaScript/jQuery 和 Rails 进行的验证。

于 2012-07-02T09:26:43.847 回答