djezzzl / database_consistency

The tool to avoid various issues due to inconsistencies and inefficiencies between a database schema and application models.
MIT License
1.02k stars 43 forks source link

MissingIndexChecker violation on polymorphic association #185

Closed kleinjm closed 1 year ago

kleinjm commented 1 year ago

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!

djezzzl commented 1 year ago

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.

kleinjm commented 1 year ago

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

djezzzl commented 1 year ago

I'm glad that it helped @kleinjm!