FriendlyID for child

168 views Asked by At

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)?

3

There are 3 answers

7
Eyeslandic On BEST ANSWER

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.

4
MZaragoza On

When you build your link_to you can call the user.slug to ensure that you get the proper info

<%= link_to gravatar_for(project.user, size: 50), project.user.slug %>

that will generate the link that you are expecting http://localhost:3000/users/random-gen-string

0
AudioBubble On

Here is an example of cities with increasing order of specificity.

 def slug_candidates
[
  :name,
  [:name, :city],
  [:name, :street, :city],
  [:name, :street_number, :street, :city]
]

end

In case of conflicting slugs it is better to use user-friendly names then UUID (e.g. 2bc2-d3dd-4f29-b2ad)