简体   繁体   English

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

[英]Rails 3 - how to validate model without database?

I have the controller home with these two actions: 我有控制器家里有这两个动作:

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

And the model: 和模型:

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

The controller: 控制器:

class HomeController < ApplicationController
  def index
  end

  def contact
    @home = Home.new
  end
end

And the form ( /views/home/contact.html.erb ) 以及表单( /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 %>

I would like to validate the form as in the case, if the model has the DB table, but unfortunately I have no experience with the case, that I have a model without DB table and is needed to validate the form... I am still getting the error 我想像情况一样验证表单,如果模型具有DB表,但是不幸的是,我没有这种情况的经验,我有一个没有DB表的模型,需要用来验证表单...我是仍然收到错误

undefined method `to_key' for nil:NilClass

Could anyone help me, please, how to make it work? 谁能帮助我,如何使其正常工作?

Thank you 谢谢

I suggest you to watch/read this railscast http://railscasts.com/episodes/219-active-model?language=en&view=asciicast which also explains your exception 我建议您观看/阅读此railscast http://railscasts.com/episodes/219-active-model?language=zh-CN&view=asciicast ,这也可以解释您的例外情况

Also I don't see your create action. 另外,我看不到您的创建操作。 Do you have the variable set when the create action fails and renders the form again? 当create操作失败并再次呈现表单时,是否设置了变量?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM