2

我正在浏览Blogger教程的“标签”部分,但有一点有点困惑:def to_s 函数(在 tag.rb 中);为什么需要它以及如何包含它。

我已经包含了相关文件的一些相关部分以作为上下文。

楷模

文章.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

标签.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

帮手

article_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

意见

新的.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 %>

显示.html.erb

标签:<%= tag_links(@article.tags) %>

4

3 回答 3

6

我明白你的意思了。当您在字符串中连接值时,您必须编写例如

"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 是 @user 的名称

于 2013-03-20T07:52:29.370 回答
2

to_s是将 Object 转换为字符串的标准 Ruby 方法。您定义to_s何时需要为您的类自定义字符串表示。例子:

1.to_s #=> "1"
StandardError.new("ERROR!").to_s #=> "ERROR!"

等等。

于 2013-03-20T03:13:57.247 回答
1

to_s是一个函数,它返回对象的等效字符串。

在这种情况下,你已经Tag.to_s定义了,它允许你做这样的事情

tag = Tag.new(:name => "SomeTag")
tag.to_s #=> "SomeTag"

当您想要来自标签的字符串时(例如,在打印到控制台时),您可以添加更多逻辑以to_s获得更友好的字符串,而不是对象哈希码。

于 2013-03-20T03:16:30.153 回答