gpt4 book ai didi

ruby-on-rails - def to_s 函数是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:39 26 4
gpt4 key购买 nike

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

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

helper

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 %>

显示.html.erb

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

最佳答案

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

"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 的名字

关于ruby-on-rails - def to_s 函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com