Search code examples
ruby-on-railsruby-on-rails-5

Incorrect key when trying to create item on polymorphic association


I have a polymorphic association discussions using the following model:

class CreateDiscussions < ActiveRecord::Migration[5.2]
  def change
    create_table :discussions do |t|
      t.references :organization, foreign_key: true
      t.references :discussable, polymorphic: true
      t.references :content, foreign_key: true

      t.timestamps
    end
  end
end

and the model is defined as

class Discussion < ApplicationRecord
  belongs_to :organization
  belongs_to :discussable, polymorphic: true
  has_one :content
end

which creates the columns discussable_id and discussable_type as I would expect.

The other side of the association is defined as

module Concerns
  module Discussable
    extend ActiveSupport::Concern

    included do
      has_many :discussions, as: :discussable, dependent: :destroy
    end
  end
end

when I try to create a discussion on my discussable I get the following error.

it 'can be added to a feature' do
  expect(feat.discussions).to be_empty
  Discussion.create(discussable: feat, content: content)

Which errors with:

 Failure/Error: Discussion.create(discussable: feat, content: content)

 ActiveModel::MissingAttributeError:
   can't write unknown attribute `discussion_id`

Rails version 5.2.3


Solution

  • Ugggg.... I was all caught up in the polymorphic association I didn't notice my content model didn't have a foreign key for the discussion.

    PEBKAC error.

    In other words, I looked completely past the fact that

    class Discussion < ApplicationRecord
      belongs_to :organization
      belongs_to :discussable, polymorphic: true
      has_one :content
    end
    

    requires that content have the discussion_id column.