【问题标题】:class method defined in model not showing up in controller模型中定义的类方法未显示在控制器中
【发布时间】:2016-12-12 10:03:53
【问题描述】:
rails version 4.2.6

我正在尝试使用 HAML 在 Rails 应用程序的视图中创建一个复选框组件。

相关查看代码:

= form_tag movies_path, :method => :get do
  Include:
  - @all_ratings.each do |rating|
    = rating
    = check_box_tag "ratings[#{rating}]"
  = submit_tag 'Refresh'

渲染此视图的控制器方法“index”应该创建实例变量“@all_ratings”,它只是所有可能的电影评分([“G”,“PG”,“PG- 13", "R"])。

相关控制器代码:

def index
    @movies = Movie.order(params[:sort_by])
    @sort_column = params[:sort_by]
    @all_ratings = Movie.all_ratings
end

方法“all_ratings”是我创建的“电影”模型的类方法:

class Movie < ActiveRecord::Base
    attr_accessible :title, :rating, :description, :release_date

    def self.all_ratings
        Movie.select(:rating).uniq.map { |movie| movie.rating }.sort
    end
end

无论我尝试什么,我都会继续收到错误:

NoMethodError in MoviesController#index
undefined method `all_ratings' for #<Class:0x000000047bcab0>

我在这里研究了几个类似的错误,它们通常似乎与类方法与实例方法的错误有关。然而,到目前为止,对这些人有效的补救措施都没有对我有效。控制器似乎无法访问我在模型中所做的任何更改。

非常感谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 model-view-controller model nomethoderror


    【解决方案1】:

    控制器中调用模型方法的三种方式:

    Samlpe.rb

    class Sample < ActiveRecord::Base
    
      ##exactly the same as defining a class method
      scope :mehtod1, -> { where(some_attribute: true) }
    
      ##class method
      def self.method2
        #code for method2
      end  
    
      ##instance method3
      def method3
        #code for method3
      end
    end
    

    SamplesController.rb

    def index
      @from_method1 = Sample.method1
      @from_method2 = Sample.method2
      @from_method3 = @from_method1.method3
    end
    

    【讨论】:

    • 嗯嗯嗯,在我看来,我已经完全使用了方法二,但它没有任何效果。 :/ 在对模型进行更改后,我是否应该运行一些命令?
    【解决方案2】:

    我终于明白了。我在不同的项目中有两个名为“movie.rb”的文件,但我编辑了错误的文件。我觉得这相当于把你的电视拆开修理它,然后发现你刚刚忘记插上电源。:|

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2015-10-19
      • 2017-02-11
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      相关资源
      最近更新 更多