我有两个资源 Controller ,我使用 slug 来表示 ID。 (Friendly_id gem )。
我可以显示路线上一个资源的路径,但不能同时显示两个资源的路径。即。
root :to => 'home#index'
match '/:id' => "properties#show"
match '/:id' => "contents#show"
基本上我想要像这样的网址,
# Content
domain.com/about-us
domain.com/terms
# Property
domain.com/unique-property-name
domain.com/another-unique-property-name
我放在上面的任何资源都有效。有办法做到这一点吗?
如果您能提供帮助,请先致谢。
最佳答案
这尚未经过测试,但请尝试在您的路线上使用约束
。
root :to => 'home#index'
match '/:id', :to => "properties#show",
:constraints => lambda { |r| Property.find_by_id(r.params[:id]).present? }
match '/:id', :to => "contests#show",
:constraints => lambda { |r| Contest.find_by_id(r.params[:id]).present? }
或者,您可以创建一个单独的类来响应 matches?
,而不是定义 lambda
过程。 (我建议将这些类放入单独的文件中,这些文件将在您的 Rails 应用程序中自动加载。)
# app/constraints/property_constraint.rb
class PropertyConstraint
def self.matches?(request)
property = Property.find_by_id(request.params[:id])
property.present?
end
end
# app/constraints/contest_constraint.rb
class ContestConstraint
def self.matches?(request)
contest = Contest.find_by_id(request.params[:id])
contest.present?
end
end
# config/routes.rb
root :to => 'home#index'
match '/:id', :to => "properties#show", :constraints => PropertyConstraint
match '/:id', :to => "contests#show", :constraints => ContestConstraint
不幸的是,这会导致额外的数据库查询(一次在路由中,一次在 Controller 中)。如果有人有减少这种情况的建议,请分享。 :)
关于ruby-on-rails-3 - 轨道路线上多个 Controller 的根路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955025/