I have a Project model that belongs to a User. A User has_many Projects. I have setup FriendlyID according to the gem instructions for User model, however it is not working in this scenario.
<%= link_to gravatar_for(project.user, size: 50), project.user %>
The above creates a link with the numerical ID of the user (project.user) instead of a friendly URL (i.e. http://localhost:3000/users/102 instead of what I want, http://localhost:3000/users/*random-gen-string*).
User.rb
file:
class User < ApplicationRecord
extend FriendlyId
friendly_id :generated_slug, use: :slugged
def generated_slug
require 'securerandom'
@random_slug ||= persisted? ? friendly_id : SecureRandom.hex(15)
end
I think the problem is that project.user
is set in the projects_controller.rb
to the user ID (via current_user.projects.build
...). If I could somehow access the Friendly ID for User in the projects_controller.rb
I may be able to save it in the database and access it like project.user_friendly_id
. Not sure..
Relevant code in projects_controller:
def create
@project = current_user.projects.build(project_params)
# code
end
What is the best way to go about making the above link link to the Friendly ID and not the user (i.e. http://localhost:3000/users/*random-gen-string* is what I want instead of http://localhost:3000/users/102)?
Update:
As discussed in the chatroom, User.find_each(&:save!)
reveals the errors when saving the User
model. In the above case, the lack of password input was preventing the User
records from being saved. Removing the validation temporarily allowed saving the User
and thus regenerating slugs.
(Original answer left for history)
You can override the to_param
method in your User
model like this
class User < ApplicationRecord
# some code
def to_param
slug
end
And then that is used to generate the link. More on that in the guides.