您的位置:首页 > 其它

to_param()函数和parameterize()函数

2016-07-25 12:01 204 查看
to_param() Link

Returns a string representing the object’s key suitable for use in URLs, or nil if persisted? is false.

class Person < ActiveRecord::Base

end

person = Person.create

person.to_param # => “1”

to_param() Link

Returns a String, which Action Pack uses for constructing an URL to this object. The default implementation returns this record’s id as a String, or nil if this record’s unsaved.

For example, suppose that you have a User model, and that you have a resources :users route. Normally, user_path will construct a path with the user object’s ‘id’ in it:

user = User.find_by(name: ‘Phusion’)

user_path(user) # => “/users/1”

You can override to_param in your model to make user_path construct a path using the user’s name instead of the user’s id:

class User < ActiveRecord::Base

def to_param # overridden

name

end

end

user = User.find_by(name: ‘Phusion’)

user_path(user) # => “/users/Phusion”

to_param(method_name = nil) Link

Defines your model’s to_param method to generate “pretty” URLs using method_name, which can be any attribute or method that responds to to_s.

class User < ActiveRecord::Base

to_param :name

end

user = User.find_by(name: ‘Fancy Pants’)

user.id # => 123

user_path(user) # => “/users/123-fancy-pants”

Values longer than 20 characters will be truncated. The value is truncated word by word.

user = User.find_by(name: ‘David HeinemeierHansson’)

user.id # => 125

user_path(user) # => “/users/125-david”

Because the generated param begins with the record’s id, it is suitable for passing to find. In a controller, for example:

params[:id] # => “123-fancy-pants”

User.find(params[:id]).id # => 123

to_param(namespace = nil) Link

Returns a string representation of the receiver suitable for use as a URL query string:

{name: ‘David’, nationality: ‘Danish’}.to_param

=> “name=David&nationality=Danish”

An optional namespace can be passed to enclose the param names:

{name: ‘David’, nationality: ‘Danish’}.to_param(‘user’)

=> “user[name]=David&user[nationality]=Danish”

The string pairs “key=value” that conform the query string are sorted lexicographically in ascending order.

This method is also aliased as to_query.

Also aliased as: to_query

parameterize(sep = ‘-‘) Link

Replaces special characters in a string so that it may be used as part of a ‘pretty’ URL.

class Person

def to_param

“#{id}-#{name.parameterize}”

end

end

@person = Person.find(1)

=> #

=> Donald E. Knuth

使用用户友好的网址。在网址显示具描述性的模型属性,而不只是 id 。

有不止一种方法可以达成:

覆写模型的 to_param 方法。这是 Rails 用来给对象建构网址的方法。缺省的实作会以字串形式返回该 id 的记录。它可被另一个具人类可读的属性覆写。

class Person

def to_param

“#{id} #{name}”.parameterize

end

end

为了要转换成对网址友好 (URL-friendly)的数值,字串应当调用 parameterize 。 对象的 id 要放在开头,以便给 ActiveRecord 的 find 方法查找。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: