Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Mongoid relationship question with Struct

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
like image 794
jmoon90 Avatar asked Aug 01 '19 03:08

jmoon90


1 Answers

belongs_to usually validates presence of the relationship, but if you already have some models that were created prior to belongs_to association being added, they won't necessarily have the association target set on them.

Separately, it is possible to destroy State documents even when there are referencing libraries (the default behavior for associations is nullify). If you delete rather than destroy State documents, this doesn't run callbacks and can leave libraries referencing deleted states.

So, ensure that all of your libraries do:

  1. Have state_id set.
  2. Have these state_ids reference existing state documents.
like image 151
D. SM Avatar answered Nov 10 '22 17:11

D. SM