Rails4 如何求字符串列的最大长度

Rails 4 how to find the maximum length of a string column

求SQL中字符串列的最大长度为:

select max(length(<column>)) from <table>

任何人都可以展示如何在 Rails 4 activerecord 甚至 squeel 中做同样的事情吗?

是这样的吗?

Model.pluck(:column).max_by(&:length)

#=> will return the longest string

另一种选择是只在 SQL:

中执行查询
Model.connection.execute("SELECT MAX(LENGTH(column)) FROM my_table")

您可以使用 Model.pluck("max(length(column))"),它不会将所有内容加载到内存中。