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
@sevenseacat is right but I believe you would have a route conflict that way:
Perhaps the route should be more like /user/:id/messages which would be a nested route of messages under user
Run
rake routesto see the generated route. In your MessagesController, you will receive :user_id and easily be able to call:Make sure you have
has_many :messagesworking in your User model.