2

我有这两个动作的控制器

  resources :home do
    collection do
      get 'index'
      get 'contact'      
    end
  end

和模型:

class Home
  include ActiveModel::Validations  
  include ActiveModel::Conversion  
  extend ActiveModel::Naming

  attr_accessor :name, :message

  validates :name, :presence => {:message => 'Name cannot be blank.'}, :allow_blank => true, :length => {:minimum => 2, :maximum => 40}
  validates :message, :presence => {:message => 'Message cannot be blank.'}, :allow_blank => true, :length => {:minimum => 10}

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

    def persisted?  
      false  
    end
end

控制器:

class HomeController < ApplicationController
  def index
  end

  def contact
    @home = Home.new
  end
end

和表格(/views/home/contact.html.erb

  <%= form_for(@home, :validate => true) do |f| %>
    <% if @home.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@home.errors.count, "error") %> prohibited this role from being saved:</h2>
          <ul>
        <% @home.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
        </ul>
      </div>
    <% end %>

    <div class="field">
      <%= f.label :name %><br />
      <%= f.text_field :name %>
    </div>
    <div class="field">
      <%= f.label :message %><br />
      <%= f.text_field :message %>
    </div>
    <div class="actions">
      <%= f.submit %>
    </div>
<% end %>

我想验证表格,如果模型有数据库表,但不幸的是我没有这个案例的经验,我有一个没有数据库表的模型并且需要验证表格......我是仍然收到错误

undefined method `to_key' for nil:NilClass

任何人都可以帮助我,请,如何使它工作?

谢谢

4

1 回答 1

1

我建议您观看/阅读此 railscast http://railscasts.com/episodes/219-active-model?language=en&view=asciicast这也解释了您的异常

我也没有看到您的创建操作。当创建操作失败并再次呈现表单时,您是否设置了变量?

于 2012-06-07T13:57:47.063 回答