I have a form that includes:
- two checkboxes
- text field to gather email addresses
I am not sure if this is the best design, but the model contains three attributes:
- email_name (type string)
- send_once (type boolean)
- send_anytime (type boolean)
I would like to save the email address if either of the two checkboxes are filled otherwise don't save anything.
Everything appeared to be working as I expected, but once I looked inside the rails console, the signup model was empty.
My log file says this:
Started POST "/pages" for 127.0.0.1 at 2012-02-01 16:34:55 -0500
Processing by PagesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"WChW/OmDPS2Td1D3x/36aCJj7V75FdiAPJ9AQvtAIS4=", "post"=>{"email_address"=>"[email protected]", "send_once"=>"0", "send_any_time"=>"1"}, "commit"=>"Create Signup"}
(0.3ms) BEGIN
(0.5ms) SELECT 1 FROM "signups" WHERE "signups"."email_address" = '' LIMIT 1
(0.3ms) ROLLBACK
Rendered pages/_form.html.erb (3.7ms)
How do I go about this? Currently the model does not save. So, specifically what should the model and the controller look like?
NOTE: I am creating a signup object inside of the Pages controller (think: newsletter).
Controller
class PagesController < ApplicationController
def index
@signup = Signup.new
end
def create
@signup = Signup.new(params[:signup])
respond_to do |format|
if @signup.save
format.html
#format.js
else
format.html {render action: :index}
end
end
end
end
Model
class Signup < ActiveRecord::Base
attr_accessible :email_address
# email_regex = come up with something
validates :email_address, presence: true,
#format: {with: email_regex}, uniqueness: {message: 'there can only be one you.'}
end
_form.html.erb
<%= form_for(@signup, as: :post, url: pages_path) do |f| %>
<% if @signup.errors.any? %>
<div id="error_explanation">
<p><%= pluralize(@signup.errors.count, "error") %> prohibited this post from being saved:</p>
<ul>
<% @signup.errors.full_messages.each do |user| %>
<li><%= user %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email_address %><br />
<%= f.email_field :email_address %>
<%= f.label :send_once %><br />
<%= f.check_box :send_once %>
<%= f.label :send_any_time %><br />
<%= f.check_box :send_any_time %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>