Home > front end >  Update params or redirect to correct URL rails
Update params or redirect to correct URL rails

Time:11-23

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!

CodePudding user response:

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

CodePudding user response:

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
  • Related