I have this library app I'm building and it has 3 classes. State, Library, and Book. The State has many libraries and Library belongs_to a State. The Library has many Books, and book is embedded in a library. However, when I make this auto_pick_job and we get to the top_free_book and call library.state. library.state is nil for some reason. I would expect to get the state back but no dice.. The way I'm calling and creating Libraries are as follows. So Library will always belong_to an existing State.
state = Stats.find(x)
library = state.libaries.new(info)
library.save_optimistic!
I'm would also be grateful for relationship help using Struct.
class State
has_many: libraries
end
class Library
belongs_to :state
end
class Book
embedded_in :library
def self.top_free_book(library_id)
library = Library.find(library_id)
library.state
end
AutoPickJob = Struct.new(:library_id) do
def perform
Book.top_free_book(library_id)
end
end
def queue_auto_pick
auto_pick_job = AutoPickJob.new(library_id)
Delayed::Job.enqueue(auto_pick_job)
end
end
belongs_tousually validates presence of the relationship, but if you already have some models that were created prior tobelongs_toassociation being added, they won't necessarily have the association target set on them.Separately, it is possible to destroy
Statedocuments even when there are referencing libraries (the default behavior for associations is nullify). If you delete rather than destroyStatedocuments, this doesn't run callbacks and can leave libraries referencing deleted states.So, ensure that all of your libraries do:
state_idset.state_ids reference existing state documents.