rails命名范围以合并字段全名

时间:2014-03-25 14:02:20

标签: ruby-on-rails ruby-on-rails-4

我的first_name模型中有last_nameAuthor字段。有时我需要输出全名,所以我想到了一个命名范围:full_name

我试过了:

scope :full_name, lambda {"#{first_name} #{last_name}"}

但是当我在作者实例上调用.full_name时,我收到一条未定义的错误消息。怎么样?

1 个答案:

答案 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"