Threading in rails console with active record does not find Model in database

I am using Rails 3 and Ruby 1.9.

I am running 2 methods in various rails tests (and in the console). The methods are called index_casesand index_new_cases, and the method bodies are shown below. The contents of the method index_new_casesprobably don't matter (I index ModelCase information using the Sunspot gem), but I leave it there for completeness.

I have 3 case_numbers. Each case_numbercorresponds ModelCaseto a database (i.e. there are 3 entries in db ModelCase).

When I use those 3 case_numbersto run tests on a method index_cases, the method index_new_casesdoes NOT retrieve any cases using the method ModelCase.where…. However, if I delete the "threading" calls in the method index_cases, the function index_new_casesnow retrieves all 3 cases and indexes them correctly.

Can someone explain to me why my threads cannot find database records? Is my slicing implementation wrong? Thank!

  def index_cases(case_numbers)
    threads = []
    case_numbers.each_slice(500) do |slice_of_case_numbers|
      threads << Thread.new(slice_of_case_numbers) do |a_slice|
        index_new_cases(a_slice)
      end
    end
    threads.each {|thr| thr.join}
  end

  def index_new_cases(case_numbers)
    cs = ModelCase.where(case_number: case_numbers).includes(:child_tables)
    puts cs.size # prints 0 with threading and 3 without threading
    Sunspot.index(cs)
    Sunspot.commit
  end

This method (without streaming) works correctly to find and index records in a database

  def index_cases(case_numbers)
    #threads = []
    case_numbers.each_slice(500) do |slice_of_case_numbers|
      #threads << Thread.new(slice_of_case_numbers) do |a_slice|
        index_new_cases(slice_of_case_numbers)
     #end
    end
    #threads.each {|thr| thr.join}
  end
+3
source share
1 answer

I had a very similar problem, although only in tests.

, ( ) - , .

. http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

, .

. , , , .

, , : http://ar.rubyonrails.org/classes/Fixtures.html

+3

Source: https://habr.com/ru/post/1785681/


All Articles