我正在关注One Month Rails并且在我的终端尝试测试时遇到困难: pin.user
然后出现以下完整错误:
frm.submit();
我的pin.rb文件是:
NoMethodError: undefined method `user' for #<Class:0x007fa59b2bd598>
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/activerecord-4.1.7/lib/active_record/dynamic_matchers.rb:26:in `method_missing'
from (irb):5
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/railties-4.1.7/lib/rails/commands/console.rb:90:in `start'
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/railties-4.1.7/lib/rails/commands/console.rb:9:in `start'
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/lennartsvanberg/.rvm/gems/ruby-2.0.0-p576@global/gems/railties-4.1.7/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:8:in `require'
from bin/rails:8:in `<main>'
我的user.rb文件是:
class Pin < ActiveRecord::Base
belongs_to :user
end
我做错了什么?
答案 0 :(得分:1)
一个pin属于一个用户,这意味着你需要在a.musicPlayer.currentTime = Double(uislider.value)
而不是pin instance
本身上调用它。
例如,Pin class
将抛出您面临的错误并且是预期的错误。要在实例上调用它,请从db创建或获取pin对象。 Pin.user
或Pin.first.user
答案 1 :(得分:0)
看起来您正试图致电Pin.user
,但您无法像这样致电user
。你可以Pin.new.user
答案 2 :(得分:0)
Class Methods
和Instance Method
之间存在差异。
班级方法:
Pin
本身。Instanse方法:
firstname
lastname
email
等等......对于关系也是如此。因此,从上面关系只能被实例调用:
pin = Pin.new
pin.user
# let's assume pin has created_at and updated_at attributes then you can say
pin.created_at
pin.updated_at
作为类方法的一个例子:
class Pin < ActiveRecord::Base
belongs_to :user
scope :last_week_create_pins, where("created_at > ?", 10.days.ago)
def self.last_week_updated_pins
where("updated_at > ?", 10.days.ago)
end
end
# you can then say, both should work and call for the class itself
Pin.last_week_create_pins
Pin.last_week_updated_pins