سؤال

Using the following code, when I try to use my code at the debugger point (attempt to use 'rating' accessor from the Song class), why do I get

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

even though Song.instance_methods clearly shows that :rating and :rating= are in the list?

-

#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
هل كانت مفيدة؟

المحلول

In below code you call rating on Song which is a class, that's why its throwing an error. Song.instance_methods clearly shows that :rating and :rating= are in the list of Song class as a instance method. you can call that method on Song.new instance, but not on Song class.

you should call rating method like this:

  @rating = Song.new.rating

  Song.new.rating = "good"

in place of this:

   @ratings = Song.rating

Hope it will help. Thanks

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top