[英]Can a custom to_s method be created for a specific association collection?
我有一個具有has_many :tags
的Entry
模型。 我希望能夠在文本輸入中列出我的標簽(即“ tag-1,tag-2”等),但是,我遇到了問題。
如果我只是用
form_for(:entry, form_options) do |f|
f.text_field :tags
end
創建了我的文本框,但其中填充了類似#<Tag:0xb79fb584>#<Tag:0xb79faddc>
,這顯然不是我想要的。
我知道我可以將to_s
方法添加到Tag:
class Tag < ActiveRecord::Base
def to_s
name # the name of the tag
end
end
但這只是給我留下像tag-1tag-2
類的東西,因為@entry.tags.to_s
仍然只引用Array#to_s
。
現在,我正在使用
f.text_field :tags, :value => @entry.tags.map(&:name).join(", ")
相反,它將顯示正確的字符串,但感覺不像是做事的“軌道方式”。 有沒有一種方法可以將自定義to_s
方法專門添加到tags
關聯?
有點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
那應該工作。
另外,您可以創建方法“ tags_string”並使其執行相同的操作,而不會濫用對象系統/維護編碼人員的大腦。
有一種更好的方法可以做到:虛擬屬性。 此示例准確顯示了如何使用虛擬屬性處理標簽關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.