3.1. Creating Users

Before a user is anything else, from the Rails perspective, it's just another resource with a model, a controller, and several views. The user can be created as a RESTful resource:

$ ruby script/generate scaffold --svn user username:string first_name:string
last_name:string email:string encrypted_password:string salt:string

As before, a number of files are created, including a migration and a new route in the routes.rb file. If you are doing these examples in order, Rails may prompt you to override the scaffold .css file. Don't do that — you've already made changes to that file that you don't want to lose. A way to avoid this issue would be to move the additions to a separate CSS file and include that file in the layout header.

The use of the --svn option will add all the newly created files to the Subversion repository. Obviously, you can leave that option off if you aren't using Subversion. If you are using Subversion but forget to use --svn, the quickest way to add all the files is to use the command svn add * --force. However, that command will add to the repository every file within your local working copy that isn't already known to Subversion, so use it with caution.

This is a minimal definition of a user: just a username, a full name, an email address, a password that will be stored in an encrypted state, and some salt (a random string encrypted with the password to make it harder to guess). I decided that the initial conception of a user in this application will allow for creating, editing, and commenting on recipes. Other user information that you might need for, say, selling things, can be added later.

Before you actually run the migration that will update the database with the new user table, you should make one addition. To associate each recipe with a user, the recipe table needs a user_id column. So, add the following lines to the newly created migration, which should be at db/migrations/003_create_users.rb. The completed migration should look like this (highlighted lines need to be added by you):

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :encrypted_password
      t.string :salt
      t.timestamps
    end

    add_column :recipes, :user_id, :integer

  end

  def self.down
    drop_table :users
    remove_column :recipes, :user_id
  end
end

Run the migration with the rake db:migrate command. Also, head into the recipe model at app/models/recipe.rb, and add the line belongs_to :user. Then go to the new user model app/models/user.rb and add the line has_many :recipes.

With everything set up, it's time to manage the first line of security in your application — the user password.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.64.126