Rails 4路由参数,看起来像一个控制器

时间:2014-08-14 15:39:14

标签: ruby-on-rails ruby-on-rails-4 routing

我的Entity模型的entity_type属性可以是HospitalClinic

我希望能够引用抽象的东西:

  • /entities
  • /entities/us
  • /entities/us/mn+md

具体:

  • /hospitals
  • /hospitals/us
  • /hospitals/us/mn+md

我在路由方面遇到了困难。我似乎无法使entity_type参数起作用。

routes.rb

get "/:entity_type/(:country_code/(:region_code))" => "entities#index", :constraints => {
  :entity_type=>["entities","hospitals","clinics"], 
  :country_code=>/[a-zA-Z]{2}([\+\,][a-zA-Z]{2})*/,
  :region_code=>/[a-zA-Z]{2}([\+\,][a-zA-Z]{2})*/
}

...

# remaining RESTful routes
resources :entities
resources :apps

entities_controller#index方法:

def index

  @entities = Entity.all

  # probably a better way to do this
  @entities = @entities.by_type(params[:entity_type]) if ( params[:entity_type].present? && params[:entity_type]!='entities')

  # location-specific; works as expected
  @entities = @entities.for_country(params[:country_code]) if params[:country_code].present?
  @entities = @entities.for_region(params[:region_code]) if params[:region_code].present?

end

对应的entity.rb方法:

# probably a better way to do this
def self.by_type(entity_type)
  return where("entity_type='#{entity_type.singularize.titleize}'") if entity_type != 'entities'
end

1 个答案:

答案 0 :(得分:0)

更改:

:entity_type=>["entities","hospitals","clinics"]

为:

:entity_type=>/(entities|hospitals|clinics)/