In Rails, when you use the resources method in routes.rb, the: id parameter is usually used by default, In some cases, you may want to change the display. This time, I will describe how to change id to name column.
↓
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
[Ruby on Rails] How to log in with only your name and password using gem devise We will change the URL based on this.
In the prerequisite article, the URL is mypage, so This time, I will dare to make the URL with an id.
config/routes.rb
get 'mypage', to: 'homes#mypage'
↓
get 'mypage/:id', to: 'homes#mypage', as: 'mypage'
app/controllers/users/registrations_controller.rb
def after_sign_up_path_for(resource)
mypage_path
end
↓
def after_sign_up_path_for(resource)
mypage_path(@user)
end
app/controllers/users/sessions_controller.rb
def after_sign_in_path_for(resource)
mypage_path
end
↓
def after_sign_in_path_for(resource)
mypage_path(@user)
end
app/controllers/homes_controller.rb
def mypage
end
↓
def mypage
@user = User.find(params[:id])
end
Now you have a URL with an id.
In order to make the URL a column, it is necessary to eliminate the same name. Then apply validation.
app/models/user.rb
validates :name, uniqueness: true
Terminal
$ rails g migration add_index_users_name
db/migrate/xxxxxxxxxxxxx_add_index_users_name.rb
class AddIndexUsersName < ActiveRecord::Migration
def change
add_index :users, :name, unique: true
end
end
Terminal
$ rails db:migrate
It is important to set find to find_by.
config/routes.rb
get 'mypage/:id', to: 'homes#mypage', as: 'mypage'
↓
get 'mypage/:name', to: 'homes#mypage', as: 'mypage'
app/controllers/homes_controller.rb
def mypage
@user = User.find(params[:id])
end
↓
def mypage
@user = User.find_by(name: params[:id])
end
In addition, to specify the link destination by name Use the to_param method,
app/models/user.rb
validates :name, uniqueness: true
#↓ Add
def to_param
name
end
This should be the same as your goal.
It is OK if you add the following to resources.
resources :users, param: :name
Now the link destination should also be displayed by name.
# Summary
By making it a character string instead of a number like this,
It is easy to understand which page you are on, which makes it more convenient.
Also, if you use a number ID in a service like SNS,
It's not a recommended method because you'll know how many registrants you have right now.
In that case, please try this method.
Also, on twitter, technologies and ideas that have not been uploaded to Qiita are also uploaded, so
I would be grateful if you could follow me.
Click here for details https://twitter.com/japwork
Recommended Posts