描述记录:to_label

当活动脚手架需要显示一条记录的描述时,它会在记录的属性中搜寻可以作为描述的字符串。这个搜索集合按顺序是::to_label:name:label:title,最后是:to_s。所以如果你的数据库结构中已经有这些字段,会自动使用它们。但是你可以随时定义一个to_label方法来定制这个字符串描述。示例:

class User < ActiveRecord::Base
  # 活动脚手架自动使用name方法描述一条记录
  def name
    "#{first_name} #{last_name}"
  end
end

class ForumPost < ActiveRecord::Base
  # 假设每个Post都有一个title属性,活动脚手架会自动使用title来描述一条记录
end

class Car < ActiveRecord::Base
  # 然而也可以定义你自己的to_label方法
  def to_label
    "#{year} #{model}"
  end
end