[英]Can a custom to_s method be created for a specific association collection?
I have an Entry
model which has_many :tags
. 我有一个具有
has_many :tags
的Entry
模型。 I want to be able to list my tags in an text input (ie. "tag-1, tag-2", etc.), however, I am running into an issue. 我希望能够在文本输入中列出我的标签(即“ tag-1,tag-2”等),但是,我遇到了问题。
If I just use 如果我只是用
form_for(:entry, form_options) do |f|
f.text_field :tags
end
My text box gets created, but is filled with something like #<Tag:0xb79fb584>#<Tag:0xb79faddc>
, which is obviously not what I'm looking for. 创建了我的文本框,但其中填充了类似
#<Tag:0xb79fb584>#<Tag:0xb79faddc>
,这显然不是我想要的。
I know I can add a to_s
method to Tag: 我知道我可以将
to_s
方法添加到Tag:
class Tag < ActiveRecord::Base
def to_s
name # the name of the tag
end
end
But that just leaves me with something like tag-1tag-2
because @entry.tags.to_s
still just refers to Array#to_s
. 但这只是给我留下像
tag-1tag-2
类的东西,因为@entry.tags.to_s
仍然只引用Array#to_s
。
Right now, I am using 现在,我正在使用
f.text_field :tags, :value => @entry.tags.map(&:name).join(", ")
instead, which will display the correct string, but doesn't feel like the "rails way" of doing things. 相反,它将显示正确的字符串,但感觉不像是做事的“轨道方式”。 Is there a way I can add a custom
to_s
method specifically to my tags
association? 有没有一种方法可以将自定义
to_s
方法专门添加到tags
关联?
kind of hacky and terrible, but you could 有点hacky和可怕,但是你可以
alias_method_chain :tags, :fancy_to_s
def tags_with_fancy_to_s
assoc = tags_without_fancy_to_s
def assoc.to_s; map(&:name).join(", "); end
assoc
end
that should work. 那应该工作。
Alternatively, you could just create the method "tags_string" and have it do the same thing without abusing the object system/the maintenance coders' brains. 另外,您可以创建方法“ tags_string”并使其执行相同的操作,而不会滥用对象系统/维护编码人员的大脑。
There's a better way to do this: virtual attributes. 有一种更好的方法可以做到:虚拟属性。 This example shows exactly how to deal with tag association using a virtual attribute.
此示例准确显示了如何使用虚拟属性处理标签关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.