NoMethodError未定义的方法'each'fn nil:NilClass

时间:2015-07-16 05:35:08

标签: ruby-on-rails ruby forms ruby-on-rails-3 validation

我在NewFormsController中遇到NoMethodError #infate,未定义的方法`each'代表nil:NilClass!

这是我的代码:

控制器:new_forms_controller.rb

class NewFormsController < ApplicationController
  def new
   @form = NewForm.new
end

  def create
    @form = NewForm.new(params[:form])
    if @form.valid?
      flash[:notice] = "Successfully created recommendation."
      redirect_to 'new_forms/new'
    else
      render :action => 'new'
    end
  end
end

型号:new_form.rb

class NewForm
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Naming

  attr_accessor :titleID, :articleID, :content, :author

  validates :titleID, :articleID, :content, :author, :presence => true
  validates :titleID, :articleID => {:minimum => 5 }

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

end

新视图:new.html.erb

<%= content_for :title, "New Article Form" %>

<%= form_for @form do |f| %>

    <% @form.errors.full_messages.each do |msg| %>
        <p><%= msg %></p>
    <% end %>

    <p>
      <%= f.label :titleID %> <br/>
      <%= f.text_field :titleID %><br/>
    </p>
    <p>
      <%= f.label :articleID %><br/>
      <%= f.text_field :articleID %><br/>
    </p>
    <p>
      <%= f.label :content %><br/>
      <%= f.text_field :content %><br/>
    </p>
    <p>
      <%= f.label :author %><br/>
      <%= f.text_field :author %><br/>
    </p>

    <p><%= f.submit "Submit"  %></p>
<% end %>

路线:routes.rb

TestBranch::Application.routes.draw do
  resources :new_forms
  root :to => "new_forms#new"
end

我正在尝试实现ActiveModel,因为我不希望我的表单对象被数据库备份,我将为数据库交互提供不同的服务。

3 个答案:

答案 0 :(得分:0)

您的模型似乎是正确的并且不包含错误,因此@form.errors包含[]

你可以检查错误

<% @form.errors.full_messages.each do |msg| %>
    <p><%= msg %></p>
<% end unless @form.errors.blank? %>

从我的评论中更新:

请尝试params[:new_form]而不是params[:form]。您的标识符:form是错误的。您的模型名为NewForm,因此您的参数名称为new_form

答案 1 :(得分:0)

你可以这样做:

 <% if @forms.errors.any? %>
   <% @form.errors.full_messages.each do |msg| %>
     <p><%= msg %></p>
   <% end %>
 <% end %>

答案 2 :(得分:0)

尝试以下代码

<% if @form.errors.any? %>
 <% @form.errors.full_messages.each do |msg| %>
    <p><%= msg %></p>
 <% end %>
<% end %>