ruby-on-rails-3 - 轨道路线上多个 Controller 的根路径

标签 ruby-on-rails-3 ruby-on-rails-3.1

我有两个资源 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/

相关文章:

ruby-on-rails - ImageMagick : ERROR: Failed to build gem native extension

ruby-on-rails - 使用 S3、Rails 和 Paperclip 时隐藏亚马逊网址

ruby-on-rails - 如何在回形针中使用原始图像网址

ruby-on-rails - rails : Use library of models

ruby-on-rails-3.1 - 导轨3.1 : Determine if asset exists

rspec - 如何在 FactoryBot 中使用 has_many 关联设置工厂

ruby-on-rails - Rails路由:仅包含自定义操作的资源

ruby-on-rails - 如何修复此语法错误?

javascript - 使用 Rails 3.1,您将 "page specific"JavaScript 代码放在哪里?

ruby-on-rails - Rails动态表单字段和AJAX提交