简体   繁体   English

rails-将方法名称传递给辅助函数

[英]rails - passing method name to helper function

docs say that options_from_collection_for_select should be used following way: 文档说应该按以下方式使用options_from_collection_for_select:

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

so, in my case for example 因此,以我为例

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

but i need to put more information to title, so what i tried to do was: 但是我需要在标题上添加更多信息,所以我试图做的是:

class Message < ActiveRecord::Base

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

end

and it works, but thing is i need strings internationalized and it's a bit more difficult with models than with controllers. 并且它可以工作,但是我需要国际化的字符串,并且使用模型要比使用控制器更困难。 now do i have to do model internationalization in this case or is it possible to get around somehow? 现在,在这种情况下,我是否必须进行模型国际化,还是有可能解决? thanks 谢谢

You can still call I18n.translate() in the model. 您仍然可以在模型中调用I18n.translate() It will give you the same result as t() helper 它将为您提供与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