You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Jul 5, 2023. It is now read-only.
ActiveRecord 5.2+ gained the optional option on belongs_to declarations. sorbet-rails infers that belongs_to relationships where optional is false means that the referenced object will always be present.
Steps to reproduce:
classEmployee < ActiveRecord::Basebelongs_to:company# required association because optional is absentendT.must(Employee.find(1).company)#=> passes, because validation enforced the presenceT.must(Employee.new.company)#=> fails because company is nilT.must(Employee.find(1).tap{|e| e.company=nil}.company#=> fails, because company is nil
In our specific case, we discovered the issue with code such as this:
classSale < ActiveRecord::Basebelongs_to:payment_termdefinit_with_defaultss=Sale.new# Sorbet complains about unreachable codes.payment_term ||= PaymentTerm.defaultsendend
Expected behavior:
belongs_to relationships should always be T.nilable(Elem), without regards to the optional option.
The calls to #belongs_to_and_required? and #has_one_and_required? would need to go, leaving only T.nilable(#{assoc_class}). I can certainly write a PR for that, with specs, but I'm not sure how you want to go about fixing this issue.
There is a class of issues with a newly created or unsaved record (Sale.new). I'm thinking about how to deal with it, eg we have 2 type: Sale and UnsavedSale. For UnsavedSale, all attributes would be nilable. It's not implemented yet though :-(
Just my 2c on the issue - I think belongs_to associations with optional: false should not be nilable as most business logic will be written for when the records have already been persisted to the DB. I personally prefer and think it's less obtrusive to treat calls where the records aren't persisted yet as an edge case than having to handle nilable values unnecessarily. In saying that, if there were a better solution where we could know when those calls would be nilable that'd be amazing
Describe the bug:
ActiveRecord 5.2+ gained the
optional
option onbelongs_to
declarations. sorbet-rails infers thatbelongs_to
relationships whereoptional
isfalse
means that the referenced object will always be present.Steps to reproduce:
In our specific case, we discovered the issue with code such as this:
Expected behavior:
belongs_to
relationships should always beT.nilable(Elem)
, without regards to theoptional
option.Versions:
The text was updated successfully, but these errors were encountered: