【问题标题】:Custom routes with id attribute具有 id 属性的自定义路由
【发布时间】:2013-02-21 08:21:57
【问题描述】:

我对如何为我的表演活动安排路线感到困惑。目前,如果我选择特定的指南来“显示”它,网址会显示

/guidelines/1

其中 1 是指南 ID

我想说

/标题

(这是正在显示的指南的标题)。我很困惑如何在我的路线中管理这个。目前我的路线有

get 'guideline/:id', to: 'guidelines#show', as: :seeguideline

但这只是显示了我提到的guideline/1,所以我意识到我做错了什么

我的观点与此链接

<%= link_to guideline.title, seeguideline_path(id: guideline.id) %>

在guidelines_controller.rb 中显示操作是

def show
    @guideline = Guideline.where(title: params[:title]).first
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @guideline }

    end
  end

路线是

ActiveAdmin.routes(self)

  devise_for :admin_user, ActiveAdmin::Devise.config


  get "guidelines/topic"
  get "guidelines/topichospital"
  get "guidelines/topicspecialty"
  get "guidelines/favourite"


  devise_for :users

  devise_scope :user do
    get 'signup', to: 'devise/registrations#new', as: :register
    get 'login', to: 'devise/sessions#new', as: :login
    get 'logout', to: 'devise/sessions#destroy', as: :logout
    get 'edit', to: 'devise/registrations#edit', as: :edit
    put 'users' => 'devise/registrations#update', :as => 'user_registration'
    get 'about', to: 'about#about', as: :about
  end

  resources :guidelines
  get 'guidelines', to: 'guidelines#index', as: :guidelines
  get 'favourites', to: "favourites#show", as: :favourites
  get 'topics', to: 'guidelines#list', as: :topics
  get 'hospitals', to: 'guidelines#listhospital', as: :hospitals
  get 'specialties', to: 'guidelines#listspecialty', as: :specialties



  root :to => 'guidelines#index'
  get '/:id', to: 'profiles#show', as: :myprofile
  get '/:title', to: 'guidelines#show', as: :seeguideline

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      如果你想匹配像'/url'这样的url,你需要把它放在你的路由文件的底部,这样它就优先级最低(即如果你有一个项目控制器,它不匹配'/projects')。理论上这是通过

      match '/:title' => 'guidelines#show', as: :seeguideline
      

      然后在你的控制器中

      def show
        @guideline = Guideline.where(title: params[:title]).first
      end
      

      那么在你的观点中,你可以使用

      seeguideline_path(@guideline.title)
      

      但您还必须注意要在 url 中使用的标题中的无效字符。

      【讨论】:

      • 谢谢 - 这一切都说得通。但它并没有把我带到正确的地方(即去 /title 但没有加载指南节目) - 它说“你正在寻找的页面不存在”
      • 你能用你的路线和你的指南控制器更新你的问题吗?
      • 这一行get '/:id', to: 'profiles#show', as: :myprofile 覆盖了您添加的路线,因此它不会转到指南控制器,而是转到配置文件控制器。
      • 啊,好的,但那是为了别的——我可以同时使用它们吗?
      • 你是对的,当我删除该行时,标题功能起作用。但是我应该怎么做才能让它们都工作呢?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多