Search code examples
ruby-on-railsdatabasemodel-view-controllerentity-relationship

Restful Authentication -- Relating User ID to Profile


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.


Solution

  • 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