Rails 3 - 如何在没有数据库的情况下验证模型?

时间:2012-06-07 13:51:43

标签: ruby-on-rails validation model

我有控制器主页这两项操作:

  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 %>

我想验证表格,如果模型有DB表,但不幸的是我没有经验,我有一个没有DB表的模型,需要验证表格..我仍然收到错误

undefined method `to_key' for nil:NilClass

有人可以帮助我,请问如何让它发挥作用?

谢谢

1 个答案:

答案 0 :(得分:1)

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

此外,我没有看到你的创作动作。如果创建操作失败并且再次呈现表单,您是否设置了变量?