Drazen
Drazen

Reputation: 2826

ActiveModel::UnknownAttributeError for namespaced model

I have 2 models which are both namespaced under "Loot"

Loot::ScreenshotCollection

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

Loot::Screenshots

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

I am getting an error when i am trying to create a new ScreenshotCollection with child screenshots

ActiveModel::UnknownAttributeError (unknown attribute 'screenshot_collection_id' for Loot::Screenshot.)

The foreign key in the database on the loot_screenshots table is "loot_screenshot_collection_id" but Rails for some reason doesn't understand this and looks for the table name without prefix.

Rails console example:

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

Upvotes: 0

Views: 455

Answers (1)

kiddorails
kiddorails

Reputation: 13014

You will need to mention foreign_key in both files:

in screenshot_collection.rb

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

In screenshot.rb:

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

Upvotes: 2

Related Questions