【问题标题】:ActiveModel::UnknownAttributeError for namespaced model命名空间模型的 ActiveModel::UnknownAttributeError
【发布时间】:2018-11-26 03:20:59
【问题描述】:

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

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.)

【问题讨论】:

  • 更改为has_many :screenshots, class_name: 'Loot::Screenshot', foregin_key: 'loot_screenshot_collection_id', dependent: :destroy

标签: ruby-on-rails activerecord namespaces activemodel


【解决方案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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2011-08-16
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    相关资源
    最近更新 更多