2012-06-07 55 views
2

我有控制器通過這兩個作用:Rails 3 - 如何驗證沒有數據庫的模型?

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 

和表單(/視圖/ 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 

任何人都可以幫助我,請,如何使它工作?

謝謝

+0

這將發佈創建操作,但不顯示它。 –

回答