Question

Currently using friendly_id on my messages table. Messages are accessed like this:

site.com/messages/id e.g. site.com/messages/8

I'd like to use it like this:

site.come/messages/username e.g. site.com/messages/terrytibbs

I've got the gem working fine as I tested it with the "body" attribute in my messages table. Sent a short message "test" and tried to access it using site.com/messages/test and it works fine.

However I need to use users usernames to do this. I was wondering if there is a way to access another models attribute as my usernames are stored in my users table. I could always create a username column in my messages table and have their usernames saved there but don't like the idea of having another username column when I already have one.

Since my tables are linked I can easily find out the message sender or recipients username using their sender_id or recipient_id as that matches their ID in my users table.

Is there a quick and easy way to do what I want to do or will I have to resort to creating a username column in my messages table?

Kind regards

Was it helpful?

Solution

@sevenseacat is right but I believe you would have a route conflict that way:

/messages/:id
/messages/:username

Perhaps the route should be more like /user/:id/messages which would be a nested route of messages under user

resources :users do
  resources :messages, only: [:index]
end

Run rake routes to see the generated route. In your MessagesController, you will receive :user_id and easily be able to call:

User.find(params[:user_id]).messages

Make sure you have has_many :messages working in your User model.

OTHER TIPS

This doesn't make sense to do and isn't what friendly_id is for - /messages/8 will load up a single instance of a message, while replacing it with /messages/terrytibbs will presumably load up a list of messages received/sent by the user terrytibbs.

I'd create just a normal collection route under messages, eg. get :username and then load the user -> get their messages, in that action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top