I am using Ruby on Rails 3.0.9 and I am trying to implement a “Contact Us” form myself. So…
… in my model file I have:
require 'active_model'
class ContactUs
include ActiveModel::Conversion
include ActiveModel::Validations
attr_accessor :email, :subject, :message
def initialize(attributes = {})
@attributes = attributes
end
validates :email,
:presence => true
validates :subject,
:presence => true
validates :message,
:presence => true
def persist
@persisted = true
end
def persisted?
false
end
end
… in my view file I have:
<%= form_for @contact_us, :url => contact_us_path do |f| %>
<%= f.text_field :email %>
<%= f.text_field :subject %>
<%= f.text_area :message %>
<% end %>
… in my router file I have:
match 'contact_us' => 'pages#contact_us', :via => [:get, :post]
… in my controller file I have:
class PagesController < ApplicationController
def contact_us
case request.request_method
when 'GET'
@contact_us = ContactUs.new
when 'POST'
@contact_us = ContactUs.new(params[:contact_us])
end
end
end
Using the above code, when I submit the form with at least a blank field (I do that in order to make it doesn’t pass validations) and the form is reloaded I don’t get those fields auto-populated. That is, after reloading the form (this happens after pressing the submit button) field values are set all to blank values.
What is the problem? Am I wrong on using the ActiveModel?
try to replace
with
EDIT:
I believe you’ll have to add the mass-assigment functionality yourself, like so:
You can actually skip this line:
self.class.send(:attr_accessor, attr.to_sym)if you want to haveattr_accessor :email, :subject, :messagelike you do already