【问题标题】:Rails isolated engine model associationsRails 隔离引擎模型关联
【发布时间】:2012-06-05 06:59:26
【问题描述】:

我有一个带有命名空间“商店”的引擎。一切都很好,除了如果我不在关联声明中添加 class_name: 'Shop::MyAssociatedModel' 会出错。 例如产品有很多product_images 所以如果产品模型看起来像这样,一切都很好:

module Shop
  class Product < ActiveRecord::Base
    has_many :product_images, :class_name => 'Shop::ProductImage'
  end
end

如果我不使用 class_name,我会收到错误:

uninitialized constant ProductImage 

在这一行:

@products.in_groups_of(3) do |products|
  ...

这是我的 engine.rb 文件:

module Shop
  class Engine < Rails::Engine
    isolate_namespace Shop
    ...
  end
end

引擎是使用 rails v 3.1.something 上的 rails generator 创建的,我升级到 rails 3.2.5

【问题讨论】:

  • 你在公共 github 存储库中有这个吗?通常 class_name 也不在字符串中,它应该是 Shop::ProductImage 而不是 'Shop::ProductImage' 并且您需要确保在 engine.rb 文件中需要 product_image.rb(我认为)
  • 对不起,它是私人的(由于 cleint 的要求)。 class_name 应该是字符串。您可以在 rails 文档中看到 - api.rubyonrails.org/classes/ActiveRecord/Associations/… 和 product_image.rb 是位于 app/models/shop/ 中的模型,因此不需要它。感谢您的评论!
  • gah .. 当我看到这个时为时已晚:(你是对的!我很抱歉。
  • 也可以是Shop::ProductImage(应该隐式调用to_s

标签: ruby-on-rails ruby-on-rails-3 associations rails-engines


【解决方案1】:

基于链接中的Rails Guides - Engines部分,如果你不添加命名空间,它会在父应用的模型中寻找类,这不是你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多