Justin
Justin

Reputation: 4940

Redirect to profile path of user with username as to_param

To show User's in my rails app I use their username in a to_param method. In the controller, I was using:

User.find_by_username(params[:id])

with routes looking like:

match '/:id', to: "users#show"....

Since today, I switched it to

Controller
  User.find_by(username: params[:username])
Routes.rb
  match '/:username', to: 'users#show',

My routes work and it's gets to the user, but when I try to update the user's settings, it redirects to the root_url and doesn't change the settings...

User's controller Update Action

def update 
  @user = User.find_by(username: params[:username])
  params[:user].delete(:password) if params[:user][:password].blank?
  if @user.update_attributes(user_params)
    flash[:success] = "Your account has been updated."
    redirect_to edit_profile_path(@user)
  else
    render 'edit'
  end
end

This was working fine until I changed it today to the find_by(username: params[:username])

where did I go wrong?

UPDATE

Routes.rb

resources :users
match '/:username', to: 'users#show', as: 'profile', via: 'get'
match '/:username/account', to: 'users#edit', via: 'get', as: 'edit_profile'

I'm assuming I need to changes the resources :users to use the username param instead of :id????

Upvotes: 1

Views: 443

Answers (1)

carpamon
carpamon

Reputation: 6633

The update action is expecting an :id parameter. You can check this by executing $> rake routes | grep user.

Add this to your routes:

put '/users/:username', to: 'users#update', as: :user

Upvotes: 1

Related Questions