How can I amend the routing from http://localhost:3000/profiles/1
to http://localhost:3000/myusername
?
I have a Profile model with the following table:
def self.up
create_table :profiles do |t|
t.string :username
t.text :interest
t.timestamps
end
end
And my routes.rb
file:
resources :profiles
I have looked at similar answers dealing with to_param, devise or nested loops or even an example in Rails 2.3, but i couldn't find a way that works.
What changes should I make to the profile/view/show.html.erb
, routes.rb
and model/profile.rb
(if any) to amend the routing from http://localhost:3000/profiles/1
to http://localhost:3000/username
? I'm learning from the basics, hence I rather not use any gems or plugins.
If you want use usernames instead of IDs try friendly_id gem.
If you want to do it by yourself, the easiest way is to override method to_param in our model to return username, and then search in your controller by username.
In model:
def to_param
username
end
In controller:
def show
@user = User.find_by_username(params[:id])
end
In routes.rb file:
match '/:id' => 'profiles#show'
This is what you need http://apidock.com/rails/ActiveRecord/Base/to_param
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With