Ruby on Rails使用资源来定义路由

时间:2014-03-11 13:48:22

标签: ruby-on-rails ruby routes

我正在开发一个保存项目,我有机构,对象和文件的模型,我在我的路径文件中使用resources来帮助管理所有这些。我遇到的问题是resources使用Ruby on Rails为其所有路由生成的:id,我想使用不同的属性。这对于学术保存和URL一致性尤为重要。例如,我希望我的机构显示网址为institutions/:identifier,而不是institutions/:id,其中:identifier是我创建的属性。问题是,我没有找到任何关于如何做到这一点的信息,只是将各个路由匹配到我想要的新路由,这似乎是一个廉价的黑客,并打破了我的很多代码。

这是我当前的路线档案:

Fluctus::Application.routes.draw do

  #match "institutions/", to: 'institutions#index', via: [:get]
  #match "institutions/", to: 'institutions#create', via: [:post]
  #match "institutions/:identifier", to: 'institutions#show', via: [:get]
  #match "institutions/:identifier", to: 'institutions#update', via: [:patch]
  #match "institutions/:identifier", to: 'institutions#update', via: [:put]
  #match "institutions/:identifier", to: 'institutions#destroy', via: [:delete]
  #match "institutions/:identifier/edit", to: 'institutions#edit', via: [:get]
  #match "institutions/:identifier/events", to: 'events#index', via: [:get]
  #match "institutions/new", to: 'institutions#new', via: [:get]
  #
  #match "objects/institution_identifier", to: 'intellectual_objects#index', via: [:get], as: "intellectual_objects_path"
  #match "objects/institution_identifier", to: 'intellectual_objects#create', via: [:post]

  resources :institutions do
    resources :intellectual_objects, only: [:index, :create], path: 'objects'
    resources :events, only: [:index]
  end

  resources :intellectual_objects, only: [:show, :edit, :update, :destroy], path: 'objects' do
    resources :generic_files, only: :create, path: 'files'
    patch "files/:id", to: 'generic_files#update', constraints: {id: /.*/}, trailing_slash: true, format: 'json'
    resources :events, only: [:create, :index]
  end

  devise_for :users

  resources :users do
    patch 'update_password', on: :collection
    get 'edit_password', on: :member
    patch 'generate_api_key', on: :member
  end

  resources :generic_files, only: [:show, :destroy], path: 'files' do
    resources :events, only: [:create]
  end

  Blacklight.add_routes(self)

  mount Hydra::RoleManagement::Engine => '/'

  authenticated :user do
    root to: "institutions#show", as: 'authenticated_root'
    # Rails 4 users must specify the 'as' option to give it a unique name
    # root :to => "main#dashboard", :as => "authenticated_root"
  end

  root :to => "catalog#index"
end

你可以看到我试图匹配单个路线而没有太多运气。到目前为止,我还没有任何运气,也查看了FriendlyID。如果有人有任何想法,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

除非我在这里遗漏了一些东西,否则你应该能够将想要使用的字符串粘贴到id所在的URL中。例如,/objects/show/1将成为/objects/show/some_string。然后在您的控制器中,您可以使用id参数找到对象:

def show
    @object = Object.where(:some_attribute => params[:id]).first
end