如何使用Ruby on Rails找到列中最长的字符串?

时间:2013-09-18 17:30:18

标签: ruby-on-rails ruby ruby-on-rails-3

Ruby从列X中找到最长字符串的最有效方法是什么?

更新:

这也很有效:

def self.length_of_longest_number
  Invoice.order("LENGTH(number) DESC").first.number.length
end

只是想知道是否有效。如果它适用于MySQL Postgres ......

2 个答案:

答案 0 :(得分:7)

这也很有效:

def self.length_of_longest_number
  Invoice.order("LENGTH(number) DESC").first.number.length
end

只是想知道是否有效。如果它适用于MySQL Postgres ......

答案 1 :(得分:6)

# Change your model name and field to your needs
Participant.order("MAX(CHAR_LENGTH(first_name)) desc").limit(1)

# works too:
Participant.order("MAX(CHAR_LENGTH(first_name)) desc").first

# and this is the most efficient to get the field directly:
Participant.limit(1).order("MAX(CHAR_LENGTH(first_name)) desc").pluck(:first_name)