【问题标题】:Method not found找不到方法
【发布时间】:2011-10-01 05:06:44
【问题描述】:

上下文:我真的对这个摸不着头脑,我查看了其他代码以了解这是如何完成的。我很欣赏这是编码的基本简单部分。老实说,到目前为止,我可能过度使用了类方法,但是 self.attrib = x 不适用于类方法。无论如何,我的问题。

我的模型中有这个:

  def self.get_user
    @people = Person.where(:mp => nil)
    @people.each do |person|
      person.get_link(person.postcode)
    end
  end

  def get_link(postcode)
    base = "http://news.bbc.co.uk/democracylive/hi/search?q="
    postcode = postcode
    target = "//a[starts-with(@class, 'name')]  /@href"
    url = base + postcode
    page = Nokogiri::HTML(open(url))
    mps = []
    page.xpath(target).each do |node|
      mps << node.text
    end
    link = mps[0]
    self.get_email(link, postcode)
  end

现在 person.get_link(person.postcode) 部分在控制台中抛出了 no method found 错误:/ 我真的不明白为什么,它显然在那里。我唯一能想到的是数据类型不正确 - 问题是我不知道如何更正。

非常感谢任何指点。

(注意:我知道这种方法可能不是最好的,我有点菜鸟,但我正在到达那里 - 缓慢但肯定:))

编辑:添加堆栈跟踪

NoMethodError: 未定义方法get_link' for #<Person:0x103633cc0> from /Library/Ruby/Gems/1.8/gems/activemodel-3.0.7/lib/active_model/attribute_methods.rb:367:inmethod_missing' 来自 /Library/Ruby/Gems/1.8/gems/activerecord-3.0.7/lib/active_record/attribute_methods.rb:46:in method_missing' from /Users/geoff/RailsWork/mpmail/app/models/postcode.rb:8:inget_user' 来自 /Library/Ruby/Gems/1.8/gems/activerecord-3.0.7/lib/active_record/relation.rb:13:in each' from /Library/Ruby/Gems/1.8/gems/activerecord-3.0.7/lib/active_record/relation.rb:13:insend' 来自 /Library/Ruby/Gems/1.8/gems/activerecord-3.0.7/lib/active_record/relation.rb:13:in each' from /Users/geoff/RailsWork/mpmail/app/models/postcode.rb:7:inget_user' 来自 (irb):2

【问题讨论】:

  • 这些方法属于什么类?
  • 你能提供一个堆栈跟踪吗?
  • @Mark Thomas - 类是 Postcode.rb
  • @Chris McCauley - 认为我在 OP 中添加了正确的内容。
  • 在 Rails 控制台试试这个:person = Person.new; person.respond_to? :get_link

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

如果我正确读取了您的堆栈跟踪,则您在 Postcode 类中定义 Person 类时调用了 get_link 方法。将 get_link 移至 Person 类,看看会发生什么。

【讨论】:

  • 噢!完全错过了。这就是为什么看到整个班级会很有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 2020-03-16
  • 2021-05-31
  • 2018-10-28
  • 2011-04-01
  • 2017-02-15
  • 2019-09-18
相关资源
最近更新 更多