database - Rails inverse_of doesn't work with conditions -
here models:
class flight < activerecord::base has_many :seats, dependent: :destroy, inverse_of: :flight end class seat < activerecord::base belongs_to :flight, inverse_of: :seats end
it seems inverse_of
works well, when i'm using conditions doesn't work:
f1 = flight.first s1 = f1.seats.first s2 = f1.seats.second s3 = f1.seats.where(id: 0..1000000).third s1.flight.equal? s2.flight => true s1.flight.equal? s3.flight => false
what explains this? how can make work?
s1.flight.equal? s2.flight => true
the above yields true because s1.flight
, s2.flight
refer the exact same ruby object.
s1.flight.equal? s3.flight
here, s1.flight
, s3.flight
refer different ruby objects. both contain same record data (including same :id
value)
the problem you're using ruby's equal?
method, when should using rails' ==
or eql?
comparators.
from the ruby object
docs ==
(aliased eql?
, equal?
)
equality — @ object level, == returns true if obj , other same object. typically, method overridden in descendant classes provide class-specific meaning.
unfortunately, equal?
variation not overridden in activerecord::base
. the rails docs ==
(aliased eql?
):
returns true if comparison_object same exact object, or comparison_object of same type , self has id , equal comparison_object.id.
you'll find has nothing :inverse_of
. simple example can try
f1 = flight.all.first f2 = flight.all.first f1.eql? f2 => true f1 == f2 => true f1.equal? f2 # direct object comparison (skips activerecord::base) => false
Comments
Post a Comment