【发布时间】:2011-12-12 14:57:57
【问题描述】:
有 STI 课程:
class Page < ActiveRecord::Base
belongs_to :user
end
class FirstTypePage < Page
end
class SecondTypePage < Page
end
每个类的控制器,
class PageController < AplicationCorroller
end
class FirstTypePageController < PageController
end
class SecondTypePageController < PageController
end
和路由:
resources :user
resource :page
end
单路径下FirstTypePageController如何处理FirstTypePage,SecondTypePageController如何处理SecondTypePage?
即
user/1/page/2 由以下人员处理: FirstTypePageController 如果“page 2”类型是“FirstTypePage”, 如果“page 2”类型是“SecondTypePage”,则通过 SecondTypePageController ?
更新:我的解决方案:
match 'user/:user_id/page/:action',
:controller=>'page/first_type_page',
:constraints=>PageConstraints.new('FirstTypePage')
match 'user/:user_id/page/:action',
:controller=>'page/second_type_page',
:constraints=>PageConstraints.new('SecondTypePage')
class PageConstraints
@@cache ||= {}
def initialize o_type
#@mutex = Mutex.new
@o_type = o_type
end
def matches?(request)
user_id = request.params[:user_id]
#add Mutex lock here
unless page_type = @@cache[user_id]
page_type = User.find(user_id).do_some_magik_to_suggest_type
@@cache[page_id] = page_type
@@cache.shift if @@cache.size > 1000
end
page_type == @o_type
end
end
我认为这个解决方案在少量页面类型上运行很快,我们可以管理内存大小,用于大量页面上的路由
【问题讨论】:
-
也就是说,可以在路由层级中为Controller在runtime中选择。类似 :controller=>User.controller_for_page(:user_id)??
标签: ruby-on-rails ruby routing sti