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)
<%= 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
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
Also I don’t see your create action. Do you have the variable set when the create action fails and renders the form again?