Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##Controller - users_controller.rb
- def register
- if request.get?
- @user = User.new
- else
- @user = User.new(params[:users])
- # According to breakpointer, the above line translates into:
- # #<User:0x227c100 @password="testt", @email="test@test.net", @new_record=true, @attributes={"installation_id"=>0, "password_hash"=>"", "email"=>""}>
- if @user.save
- # According to development.log, the above line generates the following SQL statement
- # SQL (0.000303) INSERT INTO users (`installation_id`, `password_hash`, `email`) VALUES(0, '3da541559918a808c2402bba5012f6c60b27661c', '')
- flash[:notice] = "User #{@user.email} created"
- redirect_to(:action => 'index')
- end
- end
- end
- ##Model - user.rb
- require 'digest/sha1'
- class User < ActiveRecord::Base
- attr_accessor :password
- attr_accessible :email, :password
- validates_uniqueness_of :email, :message => "already exists in the database"
- validates_presence_of :email, :password
- validates_format_of :email, :with => /^([^@\s] )@((?:[-a-z0-9] \.) [a-z]{2,})$/i,
- :message => "Invalid email address."
- def self.login(email, password)
- password_hash = encrypt(password || "")
- find(:first, :conditions => ["email = ? and password_hash = ?", email, password_hash])
- end
- def try_to_login
- User.login(self.email, self.password) ||
- User.find_by_email_and_password_hash(email, "")
- end
- def before_create
- self.password_hash = User.encrypt(self.password)
- end
- def after_create
- @password = nil
- end
- private
- def self.encrypt(password)
- Digest::SHA1.hexdigest(password)
- end
- end
- ## view - register.rhtml
- <%= form_tag %>
- <%= error_messages_for 'user' %>
- <table>
- <tr>
- <td><label>Email:</label></td>
- <td><%= text_field "users", "email" %></td>
- </tr>
- <tr>
- <td><label>Password:</label></td>
- <td><%= password_field "users", "password" %></td>
- </tr>
- <tr>
- <td><label>Password Confirmation:</label></td>
- <td><%= password_field "users", "password_confirmation" %></td>
- </tr>
- <tr>
- <td><label>Select an Installation</label></td>
- <td><%= collection_select("users", "installation_id", @installation, :id, :basename, {:prompt => "--"})%></td>
- </tr>
- <tr>
- <td></td>
- <td style="text-align: right;"><%= submit_tag "Register" %></td>
- </tr>
- </table>
- <%= end_form_tag %>
- ## Database Schema - (from) Schema.rb
- create_table "users", :force => true do |t|
- t.column "email", :string, :default => "", :null => false
- t.column "password_hash", :string, :default => ""
- t.column "installation_id", :integer, :default => 0, :null => false
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement