我正在浏览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
控制器 的
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
视图 的
new.html.erb
<%= form_for(@article, html: {multipart: true}) do |f| %>
<p>
<%= f.label :tag_list %>
<%= f.text_field :tag_list %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
show.html.erb 的
标签:<%= tag_links(@article.tags) %>
答案 0 :(得分:6)
我明白了你的意思。当您在字符串中连接值时,您必须编写 例如
"hello #{@user.name}"
因此,不是调用@ user.name你可以指定任何你必须显示用户的字符串,你可以直接在to_s方法中指定,这样你就不需要再次调用.to_s了
"hello #{@user}"
以上代码行搜索@ user类的.to_s方法并打印返回值。
同样用于路由
user_path(@user)
会给你&gt;&gt; users / 123 #其中123是@user
的id如果你写
def to_params
self.name
end
然后它会给&gt;&gt; users / john #其中john是@用户的名字
答案 1 :(得分:2)
to_s
是将Object转换为字符串的标准Ruby方法。如果需要为类创建自定义字符串表示法,请定义to_s
。例如:
1.to_s #=> "1"
StandardError.new("ERROR!").to_s #=> "ERROR!"
等等。
答案 2 :(得分:1)
to_s
是一个函数,它返回与对象相当的字符串。
在这种情况下,您已定义Tag.to_s
,这样您就可以执行此类操作
tag = Tag.new(:name => "SomeTag")
tag.to_s #=> "SomeTag"
您可以向to_s
添加更多逻辑以获得更友好的字符串,而不是当您需要来自标记的字符串时的对象哈希码(例如,在打印到控制台时)。