首页 > 解决方案 > 从模型类中传递 options_for_select 值

问题描述

我在我的 Rails 应用程序中有一个下拉菜单,如下所示。

= form_tag({:controller=>"r4c", :action=>"result"}, method: :get) do
 = label_tag(:q, "Trip Type: ")
 = select_tag(:q, options_for_select([["Single load completed trip", "r4c_001"]]), class:"select")
 = submit_tag("Get Test Details")

正如我们所看到的,我将值 [["Single....]] 值直接传递到 options_for_select。我试图从另一个类中获取这个值,比如一个模型,我已经创建了一个模型类。

require 'active_record'
class R4cOptionsModel < ActiveRecord::Base
 def country_options
    return [["Single load completed trip", "r4c_001"]]
 end
end

和视图形式

= select_tag(:q, options_for_select(R4cOptionsModel.country_options), class:"select")

但我收到一条错误消息

未定义的方法 `country_options' 用于#

这样做的正确方法是什么。谢谢你的帮助。

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

解决方案


您的方法country_options被定义为 class 中的实例方法R4cOptionsModel。因此,要么在视图中的此类的对象上调用它:

= select_tag(:q, options_for_select(@r4c_option_model.country_options), class:"select")

或者,如果您的选项更静态,最好使用以下方法将方法定义为类方法self

class R4cOptionsModel < ActiveRecord::Base
  def self.country_options
    [["Single load completed trip", "r4c_001"]]
  end
end

...并保持原样查看代码。

更新

在辅助方法中定义它(推荐)

如果您仅在视图中需要这些选项值,请使用此方法。ApplicationHelper在或任何其他帮助模块中定义它。

module ApplicationHelper
  def country_options
    [["Single load completed trip", "r4c_001"]]
  end
end

在意见中:

= select_tag(:q, options_for_select(country_options), class:"select")

推荐阅读