Reputation: 105
Relatively new to rails, so having trouble coming to a solution for this issue.
Currently have a route: /test/testing/:id
Where once a user hits the route, it will find an item in the database with that specific id and set the URL to localhost:3000/test/testing/1-name-of-this-item
However, if you just manually type in that URL eg: localhost:3000/test/testing/1
, I would like it to either redirect to /test/testing/1-name-of-this-item
OR if there is some way to change the params before the page load. But not entirely sure on how to do this.
Thank you for the help!
Upvotes: 1
Views: 224
Reputation: 105
I figured it out; there is a gem called refraction that is a middleware that allows you to alter the URL before it is processed by the app, which works well.
https://github.com/joshsusser/refraction
Upvotes: 0
Reputation: 106802
From your comment above I suppose that you have a Testing
model that has at least a column named id
and a column path
. Because you didn't mention how the path is generated I will just assume that the column is prepopulated and returns slugs like 1-name-of-this-item
and that the number prefixing the path is always in sync with the record's id.
Further, I guess that you have your routes properly set up and that /test
is a namespace and /testing
is defined as an ordinary resources :testing
. That makes me assume that a path_helper like test_testing_path
was generated by Rails.
If that is the case then it might be enough to just change your show
controller method to this:
def show
@testing = Testing.find(params[:id])
if @testing.path != params[:id]
redirect_to test_testing_path(@testing.path)
else
respond_to do |format|
format.html # show.html.erb
format.json { render json: @testing }
end
end
end
Upvotes: 1
Reputation: 274
You can try two ways to handle this
1: use the following Gem which will construct URL's based on the attribute you want https://github.com/norman/friendly_id
2: override to_param method in your model and pass the attribute you would like to display in URL path
https://apidock.com/rails/ActiveRecord/Base/to_param
Upvotes: 1