Topic: User Management Using Salted Hash Login Generator
This is a simple tutorial for RoR beginners.
This tutorial is meant for those using the Salted Hash Login Generator.
Problem: You need a login system that will show the user their information only. For example: A user has many blog entries and they should only be able to edit their blog entry.
Solution: Very simple! You just asign a foreign key to the model associated with the user (for this we'll use user_id).
After you install and configure the Slated Hash Login Generator add the following:
1. Relate the Post model with the User model using has_many and belongs_to.
/app/models/user.rb
class User < ActiveRecord::Base
has_many :posts,
:class_name => "User",
:foreign_key => "user_id"
/app/models/posts.rb
class Posts < ActiveRecord::Base
belongs_to :user,
:class_name => "User",
:foreign_key => "user_id"
2. Edit def create and def list in your Posts controller so you are adding the user's id to each post and calling the correct query for list/show.
/app/controllers/posts_controller.rb
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.user_id = @session['user'].id
...
enddef list
@posts = Post.find(:all,
:conditions => ['user_id = ?', @session['user'].id])
...
end
end
There you have it! It's that simple. If you have questions with this tutorial you can shoot me an email and I will be happy to assist you where possible.
Last edited by patrick@iws (2006-11-11 23:48:20)