我正在浏览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) %>