Ruby on rails Rails 3-如何在没有数据库的情况下验证模型?
我有控制器主页,具有以下两个操作:Ruby on rails Rails 3-如何在没有数据库的情况下验证模型?,ruby-on-rails,validation,model,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
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
请问有谁能帮我,怎么做
谢谢你我建议你看/读一下这张railscast,它也解释了你的例外情况
我也看不到你的创作动作。当创建操作失败并再次呈现表单时,是否设置了变量?这将发布到创建操作,但您不会显示它。
<%= 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