什么是def to_sfunction?
我正在阅读Blogger教程的“标签”部分,并且在一个部分上有点困惑:def to_s函数(在tag.rb中); 为什么需要它以及如何包含它。
我已经为相关文件中包含了相关文件的一些相关部分。
楷模
article.rb
class Article < ActiveRecord::Base attr_accessible :tag_list has_many :taggings has_many :tags, through: :taggings def tag_list return self.tags.collect do |tag| tag.name end.join(", ") end def tag_list=(tags_string) self.taggings.destroy_all tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq tag_names.each do |tag_name| tag = Tag.find_or_create_by_name(tag_name) tagging = self.taggings.new tagging.tag_id = tag.id end end end
tag.rb
class Tag < ActiveRecord::Base has_many :taggings has_many :articles, through: :taggings def to_s name end end
tagging.rb
class Tagging < ActiveRecord::Base belongs_to :tag belongs_to :article end
CONTROLLERS
tags_controller.rb
class TagsController < ApplicationController def index @tags = Tag.all end def show @tag = Tag.find(params[:id]) end def destroy @tag = Tag.find(params[:id]).destroy redirect_to :back end end
助手
articles_helper.rb
module ArticlesHelper def tag_links(tags) links = tags.collect{|tag| link_to tag.name, tag_path(tag)} return links.join(", ").html_safe end end
VIEWS
new.html.erb
show.html.erb
标签:
我明白了你的观点。 当您在字符串中连接值时,您必须编写例如
"hello #{@user.name}"
因此,不是调用@ user.name你可以指定你必须显示用户的任何字符串,你可以直接在to_s方法中指定,这样你就不需要再次调用.to_s了
"hello #{@user}"
上面的代码行搜索@ user类的.to_s方法并打印返回值。
同样适用于路由
user_path(@user)
会给你>> users / 123 #,其中123是@user的id
如果你写
def to_params self.name end
然后它会给>> users / john #,其中john是@用户的名字
to_s
是将Object转换为字符串的标准Ruby方法。 您希望为类创建自定义字符串表示时定义to_s
。 例:
1.to_s #=> "1" StandardError.new("ERROR!").to_s #=> "ERROR!"
等等。
to_s
是一个返回对象的字符串等效函数。
在这种情况下,您已经定义了Tag.to_s
,它允许您执行类似的操作
tag = Tag.new(:name => "SomeTag") tag.to_s #=> "SomeTag"
您可以向to_s
添加更多逻辑以获得更友好的字符串,而不是当您需要来自标记的字符串时的对象哈希码(例如,在打印到控制台时)。