具有id属性的自定义路由

时间:2013-02-21 08:21:58

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

我很困惑如何为我的节目动作整理路线。目前,如果我选择一个特定的指导方针来“展示”它,网址会说

  

/准则/ 1

其中1是指南ID

我想说

  

/标题

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

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

但是这只是我提到的指南/ 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

2 个答案:

答案 0 :(得分:1)

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

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

然后在您的控制器中

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

然后在您的观看中,您可以使用

seeguideline_path(@guideline.title)

但您还必须处理要在网址中使用的标题中的无效字符。

答案 1 :(得分:1)