ruby on rails - has_one :through association incorrectly returns nil for a new_record -
i have following models. yes, design convoluted, because we're revamping our architecture in stages; nonetheless, think principles here should work:
class translation < activerecord::base belongs_to :translation_service_option belongs_to :service, inverse_of: :translation, class_name: "translationservice" # have tried belongs_to :translation_service, inverse_of: :translation, foreign_key: :service_id end class translationservice < service # service < activerecord::base has_one :translation, inverse_of: :service # have tried inverse_of: :translation_service in conjunction above has_one :translation_service_option, through: :translation end
i trying build before_save callback on translationservice needs access translation_service_option, however, returning nil new record:
t = translation.last #=> #<translation id: 154, translation_service_option_id: 5, [...] t.service = translationservice.new #=> #<translationservice id: nil [...] t.translation_service_option #=> #<translationserviceoption id: 5 [...] t.service.translation_service_option #=> nil t.service.translation #=> #<translation id: 154 [...] t.service.translation.translation_service_option #=> #<translationserviceoption id: 5
of course, once save object, works fine, issue need access in before_save (or before_create) callback:
t.service.save t.translation_service_option #=> #<translationserviceoption [...]
so problem t.service
returns nil translation_service_option
, though t.service.translation
has valid translation_service_option
.
i t.service
doesn't have id yet, does know it's translation
object. why can't know it's translation_service_option
object? use self.translation.try(:translation_service_option)
in callback, starts messy callback uses methods used more generally, , 1 quirk find myself needing replace uses of translation_service_option
translation.try(:translation_service_option)
, seems un-railsy , negates purpose of setting has_one :through
association in first place.
is there way can set associations correctly assign t.service.translation_service_option
on initialize?
Comments
Post a Comment