def to_s 函数是什么? [英] What is the def to_s function?
问题描述
我正在浏览Blogger<的标签"部分/a> 教程,我对一个部分有点困惑:def to_s 函数(在 tag.rb 中);为什么需要它以及它是如何包含的.
I'm going through the "Tags" section of the Blogger tutorial and am a bit confused on one part: the def to_s function (in tag.rb); why it's required and how it's included.
为了上下文,我已经包含了相关文件的一些相关部分.
I've included some relevant parts of relevant files for context.
模型
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
标签.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) %>
推荐答案
我明白你的意思.当您在字符串中连接值时,您必须编写例如
I got your point. When you concatenate value in string you have to write eg
"hello #{@user.name}"
因此,不是调用@user.name,您可以指定您必须将用户显示为字符串的任何内容,您可以直接在 to_s 方法中指定,这样您就不需要再次调用 .to_s 只需编写
So instead of calling @user.name u can specify whatever u have to display user as a string you can directly specify in to_s method so that you dont need to call .to_s again just write
"hello #{@user}"
在上面的代码行中搜索@user 类的 .to_s 方法并打印返回值.
above line of code search for .to_s method for @user's class and print returning value.
同样适用于像
user_path(@user)
会给你 >> users/123 # 其中 123 是@user 的 id
will give you >> users/123 # where 123 is id of @user
如果你写
def to_params
self.name
end
然后它会给出 >> users/john # 其中 john 是@user 的名字
Then it will give >> users/john # where john is the @user's name
这篇关于def to_s 函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!