加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – rails路由上多个控制器的根路径

发布时间:2020-12-17 03:46:11 所属栏目:百科 来源:网络整理
导读:我有两个资源控制器,我使用slug来表示ID. (friendly_id gem). 我能够在路线上获得一个资源的显示路径,但不能同时拥有两个资源.即. root :to = 'home#index'match '/:id' = "properties#show"match '/:id' = "contents#show" 基本上我想要网址, # Contentdoma
我有两个资源控制器,我使用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? }

或者,您可以创建一个响应匹配的单独类?而不是定义lambda proc. (我建议将这些类放在单独的文件中,这些文件将在您的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',:constraints => PropertyConstraint
match '/:id',:constraints => ContestConstraint

不幸的是,这会产生额外的数据库查询(一次在路由中,在控制器中再次出现).如果有人建议尽量减少这个,请分享.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读