Rails 5 - Create vanity route for each instance of

2019-08-12 05:02发布

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条回答
三岁会撩人
2楼-- · 2019-08-12 05:22

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
查看更多
登录 后发表回答