ruby-on-railsrubyfriendly-id

Rails: Using friendly_id/slug with column from associated model


I've got Contact model which I want to be slugged (friendly_id gem). By using the user_name column from User model which Contact model belongs to.

class Contact < ApplicationRecord
  belongs_to :user

  extend FriendlyId
  friendly_id self.user.user_name, use: :slugged

But typing Contact.find_each(&:save) in my rails console I get this error:

NoMethodError (undefined method `user' for Contact (call 'Contact.connection' to establish a connection):Class)

How can I use my assosiated model as a slug?

Rails version: 5.2.2 Friendly_id gem: 5.2.4


Solution

  • FriendlyId always uses a method as the basis of the slug text, for your problem above I think you create method for user_name and call related field inside a method

    class Contact < ApplicationRecord
      belongs_to :user
    
      extend FriendlyId
      friendly_id :user_name
    
      def user_name
        user.user_name
      end
    end