1

I am using Devise for authentication. I have two models where a user has one profile and profile belong to user:

class User < ActiveRecord::Base
  has_one :profile, dependent: :destroy 
end 

class Profile < ActiveRecord::Base
  belongs_to :user
end

I am using nested resources e.g.

resources :users do
  resource :profile
end

To create a new user profile I use the prefix new_user_profile_path(current_user) that routes to prifile#new etc

To update a user profile I do the following

# e.g. users/123/profile
current_user.profile.update(profile_params) 

This doesn't feel right because I am not using the user_id => 123 in profile params. Should I be finding the user profile by user_id instead e.g.

@profile = Profile.find_by(user_id: params[:user_id])
@profile.update(profile_params)

Additionally, user's cannot edit other users' profile.

Thanks for the feedback.

Elvyn Mejia
  • 307
  • 4
  • 18

1 Answers1

1

current_user.profile.update(profile_params) is an acceptable way of updating the profile for the current user.

This also helps secure the profile from being edited by another user. If you base the user ID on params passed in from the query string, that is insecure and would allow any logged in user to be able to update another users profile.

For example, using restful routes anyone with access could post to /users/profiles/:id even if it wasn't their own ID.

current_user is an instance of the User model, and already contains the user_id attribute.

Jason Yost
  • 4,807
  • 7
  • 42
  • 65