在rails引发错误的视图中调用模型函数

时间:2014-06-08 14:15:17

标签: ruby-on-rails ruby-on-rails-4.1

这是模型

class Admin::Filter < ActiveRecord::Base
    validates_uniqueness_of :name
    has_many :filter_values,class_name: "Admin::FilterValue",foreign_key: "admin_filter_id"
    enum field_type: [:select_tag,:select_tag_without_search,:check_box_tag]

    def underscore_filter_name
        if self.name.split.size > 1
            self.name.replace(self.name.scan(/[A-Z][a-z]*/).join("_"))
        else
            "#{self.name.downcase}_filter"
        end
    end

end

我所说的功能是underscore_filter_name。现在我在rails console内部调用这个:Admin::Filter.first.underscore_filter_name返回一个值但是当我在视图中尝试类似时会抛出错误。以下是观点:

-@filters.each do |filter|
      %legend
        =filter.name
        -case filter.field_type
        -when "select_tag"
          = simple_form_for :"#{filter.underscore_field_name(filter)}",:url=> admin_requests_path,:method => "get",html: {:"data-filter"=>"#{filter.underscore_field_name}"}  do |f|
            = f.select("#{filter.name}", filter.filter_values.all.collect {|p| [ p.name, p.id ] }, {:include_blank => "Please select a #{filter.name}"},{:multiple => true,class: "form-control chosen-select select_tag_filter"})
        -when "select_tag_without_search"
          = select_tag "#{filter.name}", options_for_select(filter.filter_values.all.collect{ |u| [u.name, u.id]}), { :multiple => true,class: "search-free-chosen-select"}
        -when "check_box_tag"
          = simple_form_for :priority,:url=> admin_requests_path,:method => "get",html: {id: "priority_filter"}  do |f|
            = f.collection_check_boxes "#{filter.name}", filter.filter_values,:id,:name, :item_wrapper_class => 'inline'

以下行是我得到的错误:

undefined method `underscore_field_name' for #<Admin::Filter:0x007f07a322f068>

这是为什么?我正在使用Rails 4.1

2 个答案:

答案 0 :(得分:0)

您已进入视野......

underscore_field_name

但该方法的名称是

underscore_filter_name

答案 1 :(得分:0)

您已将 underscore_filter_name 定义为方法名称,并且您已在视图中输入 underscore_field_name 。错误也是如此。

将其更改为

= simple_form_for :"#{filter.underscore_filter_name(filter)}",:url=> admin_requests_path,:method => "get",html: {:"data-filter"=>"#{filter.underscore_field_name}"}  do |f|

这应解决错误。