简体   繁体   English

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

[英]calling a model function in the views in rails raising error

Here is the model 这是模型

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

The function I am talking about is underscore_filter_name . 我正在谈论的功能是underscore_filter_name Now I am calling this inside the rails console like this: Admin::Filter.first.underscore_filter_name which returns a value but when I try similarly inside the view it throws an error. 现在,我在如下所示的rails console调用此命令: Admin::Filter.first.underscore_filter_name ,它返回一个值,但是当我在视图中尝试类似操作时,它将引发错误。 Here is the view: 这是视图:

-@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'

The below line is the error I am getting: 下面的行是我得到的错误:

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

Why is this? 为什么是这样? I am using Rails 4.1 我正在使用Rails 4.1

You've got in the view... 您已经进入视野...

underscore_field_name

but the name of the method is 但方法的名称是

underscore_filter_name

You have defined underscore_filter_name as the method name and you have typed in the view as underscore_field_name . 您已将underscore_filter_name定义为方法名称,并且在视图中键入了underscore_field_name So is the error. 错误也是。

Change it to 更改为

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

This should resolve the error. 这样可以解决该错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM