I have an ActiveRecord model called Books
which has a has_one
association on authors
and a has_many
association on publishers
. So the following code is all good
books
.publishers
Now I have another AR model, digital_publishers
which is similar but which I would like to transparently use if the book's author responds to digital?
- let me explain with some code
normal_book = Book.find(1)
normal_book.author.digital? #=> false
normal_book.publishers #=> [Publisher1, Publisher2, ...]
digital_book = Book.find(2)
digital_book.digital? #=> true
digital_book.publishers #=> I want to use the DigitalPublishers class here
So if the book's author is digital (the author is set through a has_one :author
association so it's not as simple as having a has_many with a SQL condition on the books table), I still want to be able to call .publishers
on it, but have that return a list of DigitalPublishers
, so I want some condition on my has_many
association that first checks if the book is digital, and if it is, use the DigitalPublishers
class instead of the Publishers
class.
I tried using an after_find
callback using the following code:
after_find :alias_digital_publisher
def alias_digital_publisher
if self.author.digital?
def publishers
return self.digital_publishers
end
end
end
But this didn't seem to do the trick. Also, I'm using Rails 2.3.