我的first_name
模型中有last_name
和Author
字段。有时我需要输出全名,所以我想到了一个命名范围:full_name
。
我试过了:
scope :full_name, lambda {"#{first_name} #{last_name}"}
但是当我在作者实例上调用.full_name
时,我收到一条未定义的错误消息。怎么样?
答案 0 :(得分:3)
范围用于关系,以构建SQL查询,如下所示:
scope :newest, -> { order('created_at DESC').limit(10) }
Author.newest
# => returns relation of author records in `created_at DESC` order and limited to 10
相反,您需要在实例上调用的实例方法:
def full_name
"#{first_name} #{last_name}"
end
author = Author.new(first_name: 'Killer', last_name: 'Pixler')
author.full_name
# => "Killer Pixler"