Rails 5-为模型的每个实例创建虚荣路线 [英] 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.
我有一个名为Link的模型,其中包含Title,Slug和Destination。目标是要重定向的位置(mydomain.com/instagram将重定向到我的instagram帐户)。 Slug是为friendly_id自定义Slug。
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.
在route.rb的bttom处
At bttom of routes.rb
get '*id', :to => 'links#show'
在links_controller.rb中
in links_controller.rb
def show
@link = Link.find_by_slug(params[:id])
end
这篇关于Rails 5-为模型的每个实例创建虚荣路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!