渴望自我加载

时间:2018-07-06 11:45:47

标签: ruby-on-rails eager-loading ruby-on-rails-4.2

Reader.rb

has_many :book_readers, dependent: :destroy
has_many :books, -> { where('published_at < ?', Time.zone.now) },
       through: :book_readers

after_create :assign_available_books

def assign_available_books
  self.books += Book.available_to_new_readers
end

Book.rb

has_many :book_readers, dependent: :destroy
has_many :readers, through: :book_readers

def self.available_to_new_readers
  where(available_to_new:true)
    .includes(:readers)
    .select{ |a| a.readers.any? }
end

book_reader.rb

class BookReader < ActiveRecord::Base
  validates :book, uniqueness: { scope: :reader }

  belongs_to :book
  belongs_to :reader
end

readers_controller.rb

def create
  if create_reader
    redirect_to [:admin, :readers], notice: 'Created reader successfully'...
end
...
def create_reader
  reader_attributes = reader_params.clone
  admin_attributes = reader_attributes.delete(:reader_admin_attributes) || {}
  save_reader_and_admin(reader_attributes, admin_attributes)
end
...
def save_reader_and_admin(reader_attributes, admin_attributes)
  @reader, success = Reader.new(reader_attributes), false
  @reader.transaction do
    @reader.save || raise(ActiveRecord::Rollback)
    @reader.build_reader_admin(admin_attributes.merge(reader: @reader))
    @reader.reader_admin.save || raise(ActiveRecord::Rollback)
    @reader.save || raise(ActiveRecord::Rollback)
    success = true
  end
  success
end

Bullet Gem页面加载消息:

USE eager loading detected
  Reader => [:books]
  Add to your finder: :includes => [:books]
Call stack
 app/models/reader.rb:94:in `assign_available_books'
 app/controllers/admin/readers_controller.rb:67:in `block in save_reader_and_admin'
 app/controllers/admin/readers_controller.rb:66:in `save_reader_and_admin'
 app/controllers/admin/readers_controller.rb:61:in `create_reader'
 app/controllers/admin/readers_controller.rb:18:in `create'

我遇到的问题是我不知道如何急切地在assign_available_books方法中加载self。我尝试将.includes(:books)附加到其后,但得到undefined method includes

0 个答案:

没有答案