命名空间模型的ActiveModel :: UnknownAttributeError

时间:2018-06-16 16:46:02

标签: ruby-on-rails activerecord namespaces activemodel

我有2个模型,它们都在“Loot”

下命名

掉落:: ScreenshotCollection

belongs_to :agent
has_many :screenshots, class_name: 'Loot::Screenshot', dependent: :destroy
accepts_nested_attributes_for :screenshots, allow_destroy: :true

掉落::截图

belongs_to :screenshot_collection, class_name:'Loot::ScreenshotCollection', foreign_key: "loot_screenshot_collection_id"

当我尝试使用子屏幕截图

创建新的ScreenshotCollection时出现错误
ActiveModel::UnknownAttributeError (unknown attribute 'screenshot_collection_id' for Loot::Screenshot.)

loot_screenshots表中数据库中的外键是“loot_screenshot_collection_id”,但Rails由于某种原因不理解这一点并查找没有前缀的表名。

Rails控制台示例:

2.5.1 :016 > collection = Loot::ScreenshotCollection.new
 => #<Loot::ScreenshotCollection id: nil, created_at: nil, updated_at: nil> 
2.5.1 :017 > collection.screenshots.new
Traceback (most recent call last):
    1: from (irb):17
ActiveModel::UnknownAttributeError (unknown attribute 'screenshot_collection_id' for Loot::Screenshot.)

1 个答案:

答案 0 :(得分:1)

您需要在两个文件中都提到foreign_key

在screenshot_collection.rb中

has_many :screenshots, class_name: 'Loot::Screenshot', foreign_key: 'loot_screenshot_collection_id', dependent: :destroy

screenshot.rb

belongs_to :screenshot_collection, class_name:'Loot::ScreenshotCollection', foreign_key: "loot_screenshot_collection_id"