-1

使用以下代码,当我尝试在调试器点使用我的代码(尝试使用 Song 类中的 'rating' 访问器)时,为什么会得到

NoMethodError Exception: undefined method "rating" for #<Class:0xb3b7db04>

即使Song.instance_methods清楚地表明了这一点:rating并且:rating=在列表中?

-

#songs_controller.rb
class SongsController < ApplicationController    
    def index
        debugger
        @ratings = Song.rating
    end
end

-

#schema.rb
ActiveRecord::Schema.define(:version => 20111119180638) do
    create_table "songs", :force => true do |t|
        t.string   "title"
        t.string   "rating"
  end
end

-

#song.rb
class Song < ActiveRecord::Base
    attr_accessor :rating
end
4

1 回答 1

4

在下面的代码中,您调用rating了 Song 这是一个类,这就是它抛出错误的原因。 Song.instance_methods清楚地表明 :rating 和 :rating= 作为实例方法在 Song 类的列表中。Song.new您可以在实例上调用该方法,但不能在Song类上调用。

你应该像这样调用评级方法:

  @rating = Song.new.rating

  Song.new.rating = "good"

代替这个:

   @ratings = Song.rating

希望它会有所帮助。谢谢

于 2013-08-01T19:54:36.313 回答