简体   繁体   中英

Rails 4 routing parameter that looks like a controller

I have a Entity model with an entity_type attribute that can be Hospital or Clinic .

I would like to be able to refer to things in the abstract:

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

And the specific:

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

I'm having difficulty with the routing. I can't seem to get the entity_type parameter to work.

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

The entities_controller#index method:

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

Corresponding entity.rb method:

# 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

Changed:

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

to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM