Rails humanize()
为字符串添加了一个方法,如下所示(来自Rails RDoc):
"employee_salary".humanize # => "Employee salary"
"author_id".humanize # => "Author"
Run Code Online (Sandbox Code Playgroud)
我想走另一条路.我有一个用户的"漂亮"输入,我想要"去人性化"来写入模型的属性:
"Employee salary" # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title
Run Code Online (Sandbox Code Playgroud)
rails是否包含任何帮助?
在此期间,我将以下内容添加到app/controllers/application_controller.rb:
class String
def dehumanize
self.downcase.squish.gsub( /\s/, '_' )
end
end
Run Code Online (Sandbox Code Playgroud)
还有更好的地方吗?
谢谢,fd,链接.我已经实现了那里推荐的解决方案.在我的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
Run Code Online (Sandbox Code Playgroud) 我一直在努力让我的Rails创建URL来显示记录,方法是使用标题而不是URL中的ID,例如:
/职位/ A-后约-火箭
在线教程后,我做了以下工作:
因为ID不再在URL中,所以我们必须稍微更改代码.
class Post < ActiveRecord::Base
before_create :create_slug
def to_param
slug
end
def create_slug
self.slug = self.title.parameterize
end
end
Run Code Online (Sandbox Code Playgroud)
创建帖子时,标题的URL友好版本存储在数据库的slug列中.
我们还必须使用slug列更新查找以查找记录,而不是使用ID.
class ProjectsController < ApplicationController
def show
@project = Project.find_by_slug!(params[:id])
end
end
Run Code Online (Sandbox Code Playgroud)
此时它似乎工作除了显示记录,因为find_by_slug!还不存在.
我是一个极端的新手 - 我应该在哪里定义它?
任何人都可以推荐一些可以帮助我搜索引擎优化的RoR插件和/或一般圣人吗?
我使用用户输入字符串来创建一个网址,我只希望网址包含小写字母和连字符
例如example.com/this-is-a-url
在我的模型中,到目前为止我添加了:
def to_param
name.downcase.gsub(" ", "-")
end
Run Code Online (Sandbox Code Playgroud)
这使它成为小写和连字符.如何删除所有非法字符,例如'/"$£%&等等?正则表达式可能是答案,但Rails中是否已为此目的内置了一些内容?
也许我应该创建一个验证来确保'name'只是空格和字母?是否有为此目的而内置的东西?