我的Entity
模型的entity_type
属性可以是Hospital
或Clinic
。
我希望能够引用抽象的东西:
/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
答案 0 :(得分:0)
更改:
:entity_type=>["entities","hospitals","clinics"]
为:
:entity_type=>/(entities|hospitals|clinics)/