gitastic
gitastic

Reputation: 526

rails, friendly_id, devise username not showing slug

i feel like i am missing something obvious, but hopefully someone can help me out quickly.

i am trying to create a friendly_id slug for my User Model (using Devise). Here is my model:

class User < ActiveRecord::Base

  extend FriendlyId
  friendly_id :username, use: [:slugged, :finders]

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :username, :uniqueness => {:case_sensitive => false},
  :format => { with: /\A[a-zA-Z0-9]+\Z/ }

end

In my UserController:

class UsersController < ApplicationController

def show
    @user = User.find(params[:id])
end

end

When I load up the show method in my browser, it still has localhost:3000/user/3 - it does not show the slug. I know I have everything working because I have the same code in my Post Model and it works perfectly. Is there something I am missing with the User Validation / Devise that is causing it not to work?

Any help appreciated, thanks!

Upvotes: 1

Views: 1579

Answers (1)

Rubyrider
Rubyrider

Reputation: 3587

The reason is slug not saved. I think you are trying to find a legacy record which is saved before you initialized the friendly_id. But although you can generate slug and generate friendly-id for your record. Here is the process.

def should_generate_new_friendly_id?
   new_record? || slug.nil? || slug.blank? # you can add more condition here
end

after adding this method, just trying save all the record again. Friendly will call the method and will update the slug if condition matched you defined inside that block.

User.find_each(&:save!)

In your view file write the url like:

<%= link_to "USER", current_user %>

or

<%= link_to "USER", user_path(current_user.to_param) %>

Please also make sure you don't have the username blank. If there is any chance that username can be blank you can use a dynamic method where you can set the column conditionally to use for generating slug. I think that should be all! Thank you!

Upvotes: 4

Related Questions