ActiveModel::UnknownAttributeError 对于命名空间模型
ActiveModel::UnknownAttributeError for namespaced model
我有 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 table 上的数据库中的外键是“loot_screenshot_collection_id”,但 Rails 出于某种原因不理解这一点并寻找 table没有前缀的名字。
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.)
您需要在两个文件中提及 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"
我有 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 table 上的数据库中的外键是“loot_screenshot_collection_id”,但 Rails 出于某种原因不理解这一点并寻找 table没有前缀的名字。
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.)
您需要在两个文件中提及 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"