The project I am working on pretty much revolves around a user’s profile. I am still pretty new to working with Rails but, I knew there was an easier way of implementing this without having to add columns to the user table. I looked around for awhile for a tutorial or blog suggesting a painless way of adding this to an application.
I really wasn’t able to find anything so I decided to write this mini-how to.

I would first recommend that you take a look at Raaum’s Rails Reader. There is some really great documentation about ActiveRecord and how associations work. It would behoove you to follow along creating the user models and the migrations following along with the text because things will make sense that way. If you are lazy like me creating a bunch of junk models that you are just going to destroy sounds tedious I know but, it’s definitely worth the effort in the long run.

Nevertheless, I needed to be able to call a user’s profile within current_user. For example current_user.profile.body. So assuming you have already created your user model and setup the inclusion within you Application Controller. Now create your profile model and the migration accordingly.

script/generate model Profile user_id:integer body:text

Now open the Profile controller and add has_one :user somewhere after the class declaration.

class Profile < ActiveRecord::Base
has_one :user
end

It is work mentioning at this point that within the scope of this text the user will be created then redirected to the edit their profile. So if you plan to add validations in your model (ie: validates_presence_of) make sure to include

validates_presence_of :your_fields, :on => :update

Otherwise you will be unable to save the profile later.
Now add the same has_one statement to your User model but you will use

class User < ActiveRecord::Base
has_one :profile

Here is an example of how your controller might look…

class UsersController < ApplicationController
after_filter :update_session, :only => :create
before_filter :login_required, :only => [:edit, :show, :update]
before_filter :logout_required, :only => [:new, :create]
def index
@users = User.find(:all, :conditions => ['status = ?', 'active'])
end
def show
@user = User.find_by_login(params[:id])
end
def create
@user = User.new(params[:user])
@user.profile = Profile.new
self.current_user = (@user.save!)? @user : render(:action => ‘new’)
redirect_to :action => ‘edit’, :id => self.current_user.login
flash[:notice] = ‘Account successfully created!’
end
def update
self.current_user.profile.update_attributes!(params[:profile])? redirect_to(:action => ’show’, :id => self.current_user.login) : render(:action => ‘edit’)
end
end

As you can see when the create method is called it creates the Profile model and after the user is saved then redirected to the edit template.

This was the solution that worked best for me.

Post a Comment

*
*