Custom array class with assotiated objects
- by FancyDancy
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>