【问题标题】:Calling a model method with params in Rails在 Rails 中使用参数调用模型方法
【发布时间】:2016-05-25 19:48:06
【问题描述】:

我有以下问题,假设我有一个表 Users 和第二个表 UserStrings 用于本地化。 UserStrings 有以下列 {user_id, language_id, full_name}

我在 ApplicationController 中还有一个 current_language 方法,它返回当前语言的 id。

我必须使用 collection_select 并且我需要在列表中显示当前语言的用户名。

<%= fb.collection_select(:id, User.all,:id, :full_name, {}, {})%>

问题是 User 表中没有 full_name 列。我知道可以创建一个模型方法并调用它而不是名称。

<%= fb.collection_select(:id, User.all,:id, :model_method, {}, {})%>

这个模型方法我想跑这条小线

self.user_strings.find_by(:language_id => current_language).full_name

这是问题所在,我知道在模型中无法使用控制器方法,因此我无法在模型中获取 current_language。是否可以使用参数(current_language)调用 :model_method。如果没有,还有其他方法可以让这个工作吗?

ps。并且没有不可能将 current_language 重写为 Model 中的新模型方法,因为它比看起来更复杂。

提前致谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    试试这个

            def method_missing(m, *args, &block)  
                 match = m.to_s.match(/regex of languages here/)
                  if match
                    self.user_strings.find_by(:language_id => match).first_name + self.user_strings.find_by(:language_id => match).last_name
                  else
                   nil
                 end
          end  
    

    你不能直接为它定义动态方法

    【讨论】:

      【解决方案2】:

      collection_select 也接受 Proc 代替方法名称 (docs)。

      我无法尝试,但这应该可以:

      <%= fb.collection_select(:id, User.all,:id, Proc.new{ model_method(current_language) }, {}, {})%>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 2018-06-03
        • 2013-04-28
        相关资源
        最近更新 更多