Tian
Tian

Reputation: 672

Email Collector / Implementation

I am implementing a simple RoR webpage that collect emails from visitors and store them as objects.

I'm using it as a mini-project to try RoR and BDD. I can think of 3 features for Cucumber: 1. User submits a valid email address 2. User submits an existing email address 3. User submits an invalid email

My question is, for scenarios 2 and 3, is it better to handle this via the controller? or as methods in a class? Perhaps something that throws errors if an instance is instantiated in sceanrio 2 or 3?

Implementation is below, love to hear some code reviews in addition to answers to questions above. Thanks!


MODEL:

class Contact < ActiveRecord::Base
    attr_accessor :email
end

VIEW:

<h1>Welcome To My Experiment</h1>
<p>Find me in app/views/welcome/index.html.erb</p>

<%= flash[:notice] %>

<% form_for @contact, :url => {:action => "index"} do |f| %>
<%= f.label :email %><br />
<%= f.text_field :email %>
<%= submit_tag 'Submit' %>
<% end %>

CONTROLLER:

class WelcomeController < ApplicationController
  def index
    @contact = Contact.new
    unless params[:contact].nil?
      @contact = Contact.create!(params[:contact])
      flash[:notice] = "Thank you for your interest, please check your mailbox for confirmation"
    end  
  end
end

Upvotes: 2

Views: 281

Answers (2)

seigel
seigel

Reputation: 206

On another note, it is considered bad practice to bulk assign values coming back from the "params" to your model. It does allow for devious people to do unsavory things to your system sometimes.

Upvotes: 0

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

To perform the last two steps, I recommend you use rails validations. For example, try updating your model to look something like this:

class Contact < ActiveRecord::Base

  attr_accessor :email

  validates_uniqueness_of :email
  validates_format_of :email, :with => /\A(\S+)@(\S+)\Z/i

end

Upvotes: 1

Related Questions