问题
I know there has to be a cleaner way of doing this but I haven't written code in a while and am drawing a blank.
I have a model called Link that has a Title, Slug and Destination. Destination is the location to redirect (mydomain.com/instagram would redirect to my instagram account). Slug is to customize the slug for friendly_id. This is the code in my routes.rb and it works but it feels gross.
Link.all.each do |link|
get "/#{link.slug}", to: 'links#show', :id -> link.id
end
Is there a better way to accomplish this task?
回答1:
You can use single action and route to match all of your links like that.
At bttom of routes.rb
get '*id', :to => 'links#show'
in links_controller.rb
def show
@link = Link.find_by_slug(params[:id])
end
来源:https://stackoverflow.com/questions/52729750/rails-5-create-vanity-route-for-each-instance-of-model