[英]Routes, path helpers and STI in Rails 4.0
这真让我抓狂! 我有Lion
和Cheetah
这两个型号。 两者都继承自Wildcat
。
class Wildcat < ActiveRecord::Base; end
class Lion < Wildcat; end
class Cheetah < Wildcat; end
STI在这里使用。
它们都通过控制器WildcatsController
处理。 在那里,我有一个before_filer
来从params[:type]
获取before_filer
的type
以及所有其他东西来使用正确的类。
在我的routes.rb
,我创建了以下路由:
resources :lions, controller: 'wildcats', type: 'Lion'
resources :cheetahs, controller: 'wildcats', type: 'Cheetah'
如果我现在想要使用路径助手(我从路径( lions_path
, lion_path
, new_lion_path
等)获得),除了show
和new
路径之外,一切都按预期工作。 例如, lions_path
返回路径/lions
。 new
路径返回/lions/new?type=Lion
。 与show
path相同。 当我尝试输入/lions/new
到我的根域时,它会在后台正确添加类型参数。
所以,我的问题是,如果我使用路径助手,为什么Rails会将type
参数添加到url? 为什么只为new
和show
?
我正在使用一个新的Rails应用程序使用Ruby 2.0运行Rails 4.0.0。
为何使用type
? 为什么不使用继承的控制器?
resources :lions
resources :cheetahs
然后
class LionsController < WildCatsController
end
class CheetahController < WildCatsController
end
class WildCatsController < ApplicationController
before_filter :get_type
def index
@objs = @klass.scoped
end
def show
@obj = @klass.find(params[:id])
end
def new
@obj = @klass.new
end
# blah blah
def get_type
resource = request.path.split('/')[0]
@klass = resource.singularize.capitalize.constantize
end
我刚遇到这个问题。 您可以尝试关闭服务器,删除/ tmp目录并重新启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.