开发者

One to many and virtual attributes

开发者 https://www.devze.com 2023-01-09 12:19 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号