pratski
pratski

Reputation: 1488

Issue with Rails routes and models

I have 2 models - User model and Profile model. I have setup the relationship as follows:

class User
  has_one :profile
end

class Profile
  belongs_to :user
end

I have a profiles controller with 4 actions - new create edit and update. Once the User signs up or logs in he is redirected to the New action in the Profiles controller. From here how do I create a profile for that user? Specifically what should I have in my New action and Create action. Right now the route for the new action is just profiles/new which doesn't capture the Users params. I am trying to do this but its failing.

Profiles Controller

def new
    @user = User.find(params[:id])
    @profile = @user.build_profile
  end

  def create
    @profile = current_user.build_profile(params[:profile])
    if @profile.save
      redirect_to current_user
    else
      render new
    end
  end

Upvotes: 2

Views: 94

Answers (2)

theIV
theIV

Reputation: 25774

You should not be using User.find(params[:id] in your new action.

Just like in your create action below, you should be getting the User through current_user.

Is there more to the problem than not being able to properly fetch the User?

Upvotes: 2

Khaled
Khaled

Reputation: 2091

the new action in the profile controller doesn't need to get the id of the user from the params. So your controller would be like this

def new
  @user = current_user
  @profile = @user.build_profile
end

def create
  @profile = current_user.build_profile(params[:profile])
  if @profile.save
    redirect_to current_user
  else
    render new
  end
end

actually sending the id of the user to the new action could be a security hole as I could send the id of another user and create a profile for some other user in the system, which shouldn't be allowed.

Upvotes: 2

Related Questions