Stack Overflow Asked by Shin Yamagami on February 17, 2021
Profile updating redirects to a wrong URL with the original user id.
The URL of profile has users/user's_random_id/profile
and after I edit and update it on
users/user's_random_id/profile/edit
, it redirects to users/id/profile
.
For example, users/abcdef/profile/edit
redirects to users/1/profile
after updating.
"abdef" and 1 are actually the same object so it’s almost correct but I want "abcdef." I want it to redirect to users/abcdef/profile/
after updating.
The profile model belongs to the user model.
The user has to_param
and it works well for its controllers.
The route
resources :users, param: :random_id do
member do
resource :profile, only: [:show, :edit, :update]
end
end
Profile controller
def show
# @user = User.find_by(id: params[:id])
@user = User.find_by(random_id: params[:random_id])
@profile = @user.profile
end
def update
@user = User.find_by(random_id: params[:random_id])
@profile = @user.profile
if @profile.update(profile_params)
@profile.update(age: @profile.get_age)
flash[:success] = "Profile updated"
redirect_to user_profile_path
else
render 'edit'
end
end
You can override ActiveRecord::Base#to_param of a related model:
class User < ApplicationRecord
def to_param
random_id
end
# or
alias_method :to_param, :random_id
end
And change the routes param
.
resources :users, param: :random_id
Or you can use friendly_id gem.
Answered by NeK on February 17, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP