0

I am using Friendly id to allow custom queries, from the username, in my Rails app.

So say the User's username is loremipsum

rails would display this http://localhost:3000/users/loremipsum, and this works perfectly fine

but say the User's username is lorem.ipsum or lorem-ipsum

How could I make rails display, lorem.ipsum or lorem-ipsum in the url, because it currently takes the first part, and then says Couldn't find User with id=lorem

My Users controller

    class UsersController < ApplicationController


  def index

    @users = User.all


    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @movies }
    end
  end

    def search

    @movies = @search.result

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @movies }
    end
  end
  def show

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

    @movies = @search.result

  end

  def sign_up
    @user = User.new

  end

  def sign_in

  end
  def create

    @user = User.create( params[:user] )
    if @user.save
      sign_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

def edit

  @user = @current_user
end

  def update


    if @user.update_attributes(params[:user])
      sign_in @user
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end



  def destroy

    User.find(params[:id]).destroy
    flash[:success] = "User destroyed"
    redirect_to users_path
  end


  def edit 

  end 

end
PMP
  • 231
  • 6
  • 25

2 Answers2

0

Using slug for handle it, you should be able to define this on the model:

class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :username, use: :slugged

  def normalize_friendly_id(string)
    super.upcase.gsub("-", ".")
   end
end

reference : customizing friendly_id slugs

Change User.find to User.friendly.find in your controller

User.friendly.find(params[:id])

Quick Start Using Friendly_id

rails_id
  • 8,120
  • 4
  • 46
  • 84
0

This is more likely a routing issue as rails is passing through lorem as params[:id] and ipsum as format.

https://stackoverflow.com/a/7781314/308701 explains how to disable this, however the caveat is that you won't be able to request other formats such as xml, json etc ...

Community
  • 1
  • 1
Matenia Rossides
  • 1,406
  • 9
  • 35