简体   繁体   中英

Rails 5 - Create vanity route for each instance of model

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM