I'm having some trouble using nested_attributes in conjunction with the
tactical_eager_loading plugin.
Specifically, I'm trying to set a default value for a one_to_one
association in before_validation only if that association doesn't already
have an associated object via an update of a one_to_many association also
using nested attributes. However, it seems that the association is always
cleared by the time we get to before_validation so we always end up with
the default.
Here is a basic setup to illustrate the problem:
DB.create_table :albums do
primary_key :id
column :title, :text
end
DB.create_table :tracks do
primary_key :id
column :title, :text
foreign_key :album_id, :albums, null: false
end
DB.create_table :studios do
primary_key :id
column :name, :text
foreign_key :track_id, :tracks
end
Sequel::Model.plugin :nested_attributes
Sequel::Model.plugin :tactical_eager_loading
class Album < Sequel::Model
one_to_many :tracks
nested_attributes :tracks
end
class Track < Sequel::Model
many_to_one :album
one_to_one :studio
nested_attributes :studio
def before_validation
self.studio_attributes = { name: "Default Studio" } if !studio
super
end
end
class Studio < Sequel::Model
one_to_one :track
end
album = Album.create \
title: "Title",
tracks_attributes: [{
title: "First track",
studio_attributes: {
name: "MY favorite studio"
}
}]
album = Album.first
album.update \
tracks_attributes: [{
id: album.tracks.first.id,
title: "Renamed"
}, {
title: "A New track",
studio_attributes: {
name: "My second favorite studio"
}
}]
expected = "My second favorite studio"
actual = Track[title: "A New track"].studio.name
raise "expected: #{expected}, actual: #{actual}" if expected != actual
For the new track being added in the update, the studio= setter is being
called twice because the studio association is nil in
Track#before_validation. We tracked it down to the
initialize_association_cache clearing the association via
tactical_eager_loading after studio_attributes= is first called.
Is there a more conventional way to do this you could suggest or is it
indeed a bug?
Thank you for any help you can provide!
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/sequel-talk/9067d8b9-be1e-4bf4-a84a-50841940787cn%40googlegroups.com.