djezzzl/database_consistency

MissingIndexChecker violation on polymorphic association

Closed this issue · 3 comments

Violation: MissingIndexChecker fail Project locations associated model should have proper index in the database

Schema

  create_table "locations", force: :cascade do |t|
    t.decimal "latitude"
    t.decimal "longitude"
    t.string "owner_type", null: false
    t.bigint "owner_id", null: false
    t.index ["owner_type", "owner_id"], name: "index_locations_on_owner"
  end

Location model has belongs_to(:owner, polymorphic: true)

Project model

  has_many(
    :locations,
    inverse_of: :owner,
    foreign_key: :owner_id,
    dependent: :destroy,
  )

I'm not sure what else is missing. There is no column pointing to the location model from the project model. Any ideas what the violation means? Thanks in advance and thanks again for the gem!

Hi @kleinjm,

Thank you for using the gem and reporting the issue!

I'm sorry it took me long to look at it.

I'm not sure what else is missing. There is no column pointing to the location model from the project model. Any ideas what the violation means?

Looking at your association, I think the message is correct because your association is not defined as polymorphic.

has_many(
    :locations,
    inverse_of: :owner,
    foreign_key: :owner_id,
    dependent: :destroy,
  )

It should be

has_many :locations, as: :owner, dependent: :destroy

You can read more about polymorphic associations here: https://guides.rubyonrails.org/association_basics.html#polymorphic-associations.

Please let me know if that did or didn't help. Feel free to reopen the issue if needed.

That did it! Thanks a lot for the pointer. I confused inverse_of with as

I'm glad that it helped @kleinjm!