Hi,

Is eager loding available for N : N relation?
Or is it possible to emurate eager loading manually?

For example:
  * Book, Author, and Writing models classes exist
  * Book : Author = N : N (through Writing)

In this case, the following code generates a lot
of 'select * from authors ...' statements.

  Book.all.each do |book|
    book.authors.each {|author| p author }
  end
  #=> select * from books;
  #=> select * from authors ... where writings.book_id = 1
  #=> select * from authors ... where writings.book_id = 2
  #=> select * from authors ... where writings.book_id = 3
  #=> ...

So I tried the following code:

  module Enumerable
    def index_by
      hash = {}
      self.each do |item|
        hash[yield(item)] = item
      end
      hash
    end
  end

  ## get all books and authors
  books_by_id   = Book.all.index_by {|book| book.id }
  authors_by_id = Author.all.index_by {|author| author.id }
  ## group them
  books = {}
  authors = {}
  Writing.all.each do |writing|
    book   = books_by_id[writing.book_id]
    author = authors_by_id[writing.author_id]
    (books[author.id] ||= []) << book
    (authors[book.id] ||= []) << author
  end
  ## set association manually
  all_books = Book.all
  all_books.each {|book| book.authors = authors[book.id] }
  all_authors = authors.all
  all_authors.each {|author| author.books = books[author.id] }


But I got the following error:

  DataMapper::Associations::ImmutableAssociationError: You can not
modify this association


Could you give me any adivces?

--
regards,
makoto kuwata


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"DataMapper" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/datamapper?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to