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

Database_сonsistency Gem Does Not Detect Some Validations #223

Open eternalyoung opened 7 months ago

eternalyoung commented 7 months ago

When running the database_consistency gem in my project, it indicates the absence of validations for certain fields in my model, even though I'm sure they are present. After debugging the gem, I discovered that at the time of validation checking, the model indeed lacks validations.

# RAILS CONSOLE
3.1.2 :001 > Relationship.validators
 => 
[#<ActiveRecord::Validations::PresenceValidator:0x00000001113ea3e8
  @attributes=[:descendant],
  @options={:message=>:required}>,
 #<ActiveRecord::Validations::PresenceValidator:0x000000011150b628
  @attributes=[:ancestor],
  @options={:message=>:required}>,
 #<ActiveRecord::Validations::PresenceValidator:0x00000001115083b0
  @attributes=[:ancestor_id, :descendant_id, :generations],
  @options={}>,
 #<ActiveRecord::Validations::UniquenessValidator:0x0000000111502870
  @attributes=[:ancestor_id],
  @klass=Relationship (call 'Relationship.connection' to establish a connection),
  @options={:scope=>[:descendant_id, :generations]}>] 
# IRB AT VALIDATIONS CHECK IN GEM
3.1.2 :010 > model
 => Relationship(ancestor_id: integer, descendant_id: integer, generations: integer, created_at: datetime, id: integer)                                                                       
3.1.2 :011 > model.validators
 => 
[#<ActiveRecord::Validations::PresenceValidator:0x000000010adea480           
  @attributes=[:ancestor],                                                   
  @options={:message=>:required}>,                                           
 #<ActiveRecord::Validations::PresenceValidator:0x000000010adf36c0           
  @attributes=[:descendant],                                                 
  @options={:message=>:required}>] 

This issue occurs when adding some code to a controller that is unrelated to this model. It's a very strange behavior that I'm encountering for the first time.

djezzzl commented 7 months ago

This issue occurs when adding some code to a controller that is unrelated to this model.

It could be that lazy loading all your constants don't help load all your code.

Could you please check how those missing validations are defined?

There are two options to improve this:

P.S. Happy Christmas and New Year time!

eternalyoung commented 6 months ago

You nailed it. If you use a custom runner with loading like Dir[Rails.root.join("app/**/*.rb")].each { require _1 }, everything works correctly.

If you need any additional information to fix this issue, please feel free to ask.