簡體   English   中英

rails-將方法名稱傳遞給輔助函數

[英]rails - passing method name to helper function

文檔說應該按以下方式使用options_from_collection_for_select:

options_from_collection_for_select(collection, value_method, text_method, selected = nil) 

因此,以我為例

options_from_collection_for_select(@messages,'id','title')

但是我需要在標題上添加更多信息,所以我試圖做的是:

class Message < ActiveRecord::Base

 def proper_title
  self.name+", updated at "+self.updated_at
 end

end

並且它可以工作,但是我需要國際化的字符串,並且使用模型要比使用控制器更困難。 現在,在這種情況下,我是否必須進行模型國際化,還是有可能解決? 謝謝

您仍然可以在模型中調用I18n.translate() 它將為您提供與t()幫助器相同的結果

# Message.rb
def proper_title
  I18n.translate("message.proper_title", :name => self.name, :updated_at => self.updated_at)
end

# en.yml
en:
  message:
    proper_title: "{{name}}, updated at {{updated_at}}"

# view
options_from_collection_for_select(@messages,'id','proper_title')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM