0

this is my model User

class User < ApplicationRecord
  extend FriendlyId
    friendly_id :name
end

the user name is not uniq.

i want my url like this:

http://localhost:3000/users/myname

this is my controller:

class UsersController < ApplicationController
before_action :set_user

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

the URL is shown fine, just the way i want, but the problem is when i try to delete a user, the console server shows a "rollback" i notice that this is because there are two or more users with the same name so It can delete the user. So my problem now that I have implemented gem friendly_id is that it searchs and set_user by name but i want to set_admin by ID so i can delete by id (this way it does not matter if there are many users with the same name). This problem is repeated in my other models too.

How can avoid this behavoir, I need to set model by id but to show the name or encrypt the id in the url. Do you recomend me other gem or how should i implement correctly. (is not an option to set name as uniq). thanks

matQ
  • 597
  • 2
  • 13
  • 27
  • The word "ID" means identity, so it must be unique. If you allow `name` not to be unique, then it should not be chosen as ID in the first place, no matter if it's "friendly" or not. – Aetherus Jan 21 '18 at 00:34
  • so how can i hide or encrypt the id in the url? but in my controller still searching by id? – matQ Jan 21 '18 at 00:39
  • Before you try to encrypt the URL, you should ask yourself why you need to do so. If your answer is "to prevent end users from accessing unauthorized data by brute-forcing URLs", then you should add authentication and authorization to your application (using Devise or Knock) and keep the URLs simple. – Aetherus Jan 21 '18 at 00:54
  • maybe to hide information to users, for example quantity of transactions or products in your db – matQ Jan 21 '18 at 00:58
  • How can a traditional ID expose such things? – Aetherus Jan 21 '18 at 00:58

1 Answers1

0

As per my understanding, friendly id uses uniqueness validation at db level

https://github.com/norman/friendly_id/blob/aff0564584e84ffa505e6e278b65ca3c4ee5d698/lib/friendly_id/migration.rb#L12

If you already have users with same name, you should delete those entries. (This is much similar to condition where we try to put unique index to a column in db where same entry values already exist)

Then install friendly_id gem, and make entries. I am sure slugs created by gem wont repeat so every record will be unique and you will be able to delete record using id Too

yogendra689
  • 106
  • 1
  • 7