Rails 为字符串添加了一个 humanize()
方法,其工作原理如下(来自 Rails RDoc):
"employee_salary".humanize # => "Employee salary"
"author_id".humanize # => "Author"
我想走另一条路。我有来自用户的“漂亮”输入,我想将其“非人性化”以写入模型的属性:
"Employee salary" # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title
rails 对此有任何帮助吗?
更新
同时,我将以下内容添加到 app/controllers/application_controller.rb:
class String
def dehumanize
self.downcase.squish.gsub( /\s/, '_' )
end
end
还有更好的地方放吗?
解决方案
谢谢,fd ,对于link 。我已经实现了那里推荐的解决方案。在我的 config/initializers/infections.rb 中,我在末尾添加了以下内容:
module ActiveSupport::Inflector
# does the opposite of humanize ... mostly.
# Basically does a space-substituting .underscore
def dehumanize(the_string)
result = the_string.to_s.dup
result.downcase.gsub(/ +/,'_')
end
end
class String
def dehumanize
ActiveSupport::Inflector.dehumanize(self)
end
end
最佳答案
string.parameterize.underscore
会给你相同的结果
"Employee salary".parameterize.underscore # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title
或者您也可以使用稍微简洁一点的(感谢@danielricecodes)。
- Rails < 5
员工工资".parameterize("_") # => employee_salary
- Rails > 5
员工工资".parameterize(separator: "_") # => employee_salary
关于ruby-on-rails - Rails 是否有与 'humanize' 相对的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2835786/