首先,什么你指的是一种叫Single Table Inheritance
:(!对于任何谷歌搜索的引用)
#app/models/article.rb
class Article < ActiveRecord::Base
# needs a "type" column
end
#app/models/foo.rb
class Foo < Article
end
#app/models/bar.rb
class Bar < Article
end
都将使用文章表。
对此有几种修复方法。
您的主要问题是控制器。
你一直在试图确定使用哪种控制器结构。如果您使用上述设置(,那么您的不需要更改模型中的任何内容),您将能够明确区分这两种模型。唯一剩下的就是确定使用哪条路线。
要简洁,我会用我自己的模块找到Article
或Post
,并发送请求到单控制器:
#config/routes.rb
%w(foo bar).each do |o|
get "/#{o}/:id", to: Dispatcher.new(self), as: o.to_sym #-> url.com/foo/1 & url.com/bar/2
end
#lib/dispatcher.rb
class Dispatcher
#http://blog.arkency.com/2014/01/short-urls-for-every-route-in-your-rails-app/
##########################################
#Init
def initialize(router)
@router = router
end
#Env
def call(env)
id = env["action_dispatch.request.path_parameters"][:id]
model = env["action_dispatch.request.path"].gsub("/", "") #-> /foo
record = model.titleize.constantize.find id #-> looks up in the specific model (foo/bar)
if record
ArticlesController.action("show").call(env)
else
raise ActiveRecord::RecordNotFound
end
end
end
最后,你就可以通过以下为articles#show
操作:
#app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def show
model = request.path.gsub("/", "") #-> "foo"
@article = model.titleize.constantize.find params[:id]
end
end
感谢您的支持。尽管您引用的文件位于'lib'文件夹中,我还是得到了一个“未初始化的常量Dispatcher”。它是否需要位于其他地方与项目一起加载? – UserDuser
您可能需要将此添加到'config/application.rb' - 'config.autoload_paths + = Dir [“#{config.root}/lib”]':) –