Search code examples
rubysequel

Association block is called only once


I am using Sequel and I have model defined like this:

class A < Sequel::Model
  one_to_one :lang, class: ALang, key: :a_id,
             graph_join_type: :inner do |ds|
               ds.where(ALang__lang: I18n.locale.to_s)
             end
  delegate :title, :titleSanitized, :description, to: :lang
  # ...
end


I18n.lang = :de
A.eager(:lang).all 
# block is called ("ds.where(ALang__lang: I18n.locale.to_s)" code)
# database was queried (I can see the query in logs) 
I18n.lang = :en
A.eager(:lang).all 
# block is not called
# database was queried (I can see the query in logs)

Is it bug or feature? Or am I doing something wrong?

Thank you


Solution

  • In this case, the block is eagerly evaluated and the resulting dataset is cached. To delay the evaluation of the current locale, you need to use a delayed evaluation:

    one_to_one :lang, class: ALang, key: :a_id,
             graph_join_type: :inner do |ds|
               ds.where(ALang__lang: Sequel.delay{I18n.locale.to_s})
             end
    

    I've updated Sequel's documentation to reflect this.