Custom array class with assotiated objects

Posted by FancyDancy on Stack Overflow See other posts from Stack Overflow or by FancyDancy
Published on 2010-04-14T15:41:13Z Indexed on 2010/04/14 15:43 UTC
Read the original article Hit count: 370

I have a simple structure, it's just an array of model's objects.

For example, it's a users with books. @books = Book.find(:all, :include => :users)

I need to check, does user have a book? I have written a helper method:

def has_book?(user_id)
  @books.select{|b| b.user_id == user_id}.any?
end

Then, i need to get only books from selected library

def in_library(n)
  @books.select{|b| b.library == n}
end

I have tried to make custom Array class:

class BooksList < Array
  def initialize(books)
    self << books
  end

  # its my custom methods

  def has_book?(user_id)
    self.select{|b| b.user_id == user_id}.any?
  end

  def in_library(n)
    self.select{|b| b.library == n}
  end

end

It works, but i have only one problem. I can't access Book's assotiated object (user). So i can't write:

@books = BookList.new(Book.find(:all, :include => :users))
@books.first.user.id # it says undefined method `user' for #<Array:0x104b43e08>

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails