Tutorial :One to many and virtual attributes



Question:

I have a model book with a one to many relation with authors.

I want to add an attribute to a book instance called last_author that puts the latest author and can be implemented as

def last_author  self.authors.last.name  end  

but when i do Book.find(1).inspect i cant see the field last_author, but i want it. how can achieve that without writing a query to active record?


Solution:1

Why exactly you need an attribute instead of function? With the code you provided Book.find(1).last_author should return what you want.

If you do insist on having an attribute, you can set it manually before using, like book.last_author = book.authors.last.name. Not saying I recommend it, though.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »