0

I am trying to build vanity urls with FriendlyId gem for a specific model Teacher to display

 www.mysite.com/teachers/{first_name}-{last_name}

instead of

wwww.mysite.com/teachers/{id}

The problem that I encounter is that the information on the {first_name} / {last_name} is stored in the table Contact accessible through User and not in Teacher's one. The relation between the tables is as follows:

- Teacher belongs_to :user 
- User has_one :contact

I added in my Teacher model:

 extend FriendlyId
 friendly_id :full_name_to_url, use: :slugged

So FriendlyId calls the method full_name_to_url to create the slug:

def full_name_to_url
"#{self.user.contact.first_name.downcase.gsub(" ","-")}-#{self.user.contact.last_name.downcase.gsub(" ","-")}"
end

I received the following message when trying to apply and save all the changes to the already existing records: Teacher.find_each(&:save)

 NoMethodError: undefined method `contact' for nil:NilClass

I guess there is something wrong with my method?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user6877257
  • 45
  • 1
  • 4

0 Answers0