class 模型中定义的方法未显示在控制器中

class method defined in model not showing up in controller

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" 是我创建的 "Movie" 模型的 class 方法:

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>

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

非常感谢。

controller中调用模型方法的三种方式:

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

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