Rails 5 - Create vanity route for each instance of model

萝らか妹 提交于 2019-12-24 10:17:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!