views:

43

answers:

2

Hey Guys,

I'm new to Ruby on Rails...I've been playing around with developing a social networking type app....I just added Restful Authentication to my app successfully..Now I would like to create a model/controller where each User once logged in can create/edit their own profile.

So I created the model and controller...the code in the Profile controller looks like this:

def new
  @profile = Profile.new(params[:user_id])
  if request.post?
      @profile.save
      flash[:notice] = 'Profile Saved'
      redirect_to :action => 'index'
  end
end

I am trying to connect the user_id [of restful auth.] of which ever user is in the session to the column user_id I made in the profile model. I have already add the "has_one :profile" to the user model and the "belongs_to :user" in the profile model...but its not adding the profile. I'm kind of stuck since I'm relatively new to this...should I add some thing to the session model or controller?

any help or ideas or places for research would really be appreciated...

Connecting new models to already existing ones is pretty important and I'd like to figure this thing out.

A: 

First, if you're just getting started, you should seriously consider using Authlogic over Restful Authentication. There are no generators, and you end up with very easy to manage code.

For this specific issue: the creation of the record @profile.save should be in the create action. new is about setting up an instance of the model for a form to edit it on the new.html.erb view.

You may also have access to a method called @current_user (or a function called current_user). If you do, you can ease things a little bit by doing this:

@profile = current_user.profile.build

The method build will create the association between the user and the profile for you.

Tim Sullivan
+2  A: 

By default a new action is an HTTP GET, so your request.post? block gets bypassed. The request.post? is extraneous anyway (for basic purposes), so I'd get rid of that completely and move the rest of the save code to your create action.

def new
  @profile = Profile.new
end

def create

  @user = User.find(params[:user_id])
  @profile = Profile.create(@user, params[:profile]) # or whatever params you use in your form
  # you can also do @profile = @user.profile.create(params[:profile]) here
  # sans @user find: @profile = current_user.profile.create(params[:profile])

  if @profile.save
    flash[:notice] = 'Profile Saved'
    redirect_to :action => 'index'
  else
    flash[:warning] = 'Could not save profile'
    redirect_to :back # or wherever
  end

end
Eric Hill