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?
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.
精彩评论