views:

14

answers:

1

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?

A: 

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.

Nikita Rybak
It's a long story, but i need it! (for to_json.. but it's long to explain)
tapioco123
Oh, I see. Personally, I would go with a helper method to do conversion, then.
Nikita Rybak
how i have to write them?
tapioco123