在我的 RoR3 应用程序中,我有一个名为 NS1 的命名空间,以便我拥有以下文件系统结构:
ROOT_RAILS/controllers/
ROOT_RAILS/controllers/application_controller.rb
ROOT_RAILS/controllers/ns/
ROOT_RAILS/controllers/ns/ns_controller.rb
ROOT_RAILS/controllers/ns/profiles_controller.rb
我希望“ns_controller.rb”继承自应用程序 Controller ,因此在“ns_controller.rb”文件中我有:
class Ns::NsController < ApplicationController
...
end
这是正确的方法吗?无论如何,如果我处于这种情况...
在
ROOT_RAILS/config/routes.rb
我有:namespace "ns" do
resources :profiles
end
@profile
是一个 ActiveRecord:@profile.find(1).name
=> "Ruby on"
@profile.find(1).surname
=> "Rails"
在
application_controller.rb
我有:class ApplicationController < ActionController::Base
@profile = Profile.find(1)
end
在
ns_controller.rb
我有:class Ns::NsController < ApplicationController
@name = @profile.name
@surname = @profile.surname
end
...
@name
和 @surname
未设置变量。 为什么?
最佳答案
除非您没有在此处显示某些代码,否则您将尝试在类主体中设置实例变量而不是实例方法,这意味着该变量在 Controller 操作(即实例方法)中将不可用。
如果您想要可以继承的 find 方法,您可以执行以下操作:
class ApplicationController < ActionController::Base
def load_profile
@profile = Profile.find(params[:id])
end
end
class Ns::NsController < ApplicationController
before_filter :load_profile
def show
# @profile assigned a value in load_profile
end
end
关于ruby-on-rails - 使用 Ruby on Rails 3 的命名空间中的类继承怎么可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4658856/