ruby-on-rails - 使用 Ruby on Rails 3 的命名空间中的类继承怎么可能?

标签 ruby-on-rails ruby class inheritance namespaces

在我的 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/

相关文章:

ruby-on-rails - 用于构建新操作的 rspec 匹配器

mysql - 如何从数据库中检索至少存在 10 个列值中的 3 个的记录?

ruby-on-rails - 我如何使用 Faye 列出活跃订阅者?

ruby - 无法使用 Watir 单击相同的元素类

ruby-on-rails - 子文件夹中的子类模型不会自动加载

c++ - map可以包含类对象还是类对象?

ruby-on-rails - 如何使用 RSpec 测试 Rails 3.2 ActionMailer 是否呈现正确的 View 模板?

ruby-on-rails - Paypal-express gem,在开发中工作但不在生产中

C++类继承

c++ - 不是类或命名空间名称