Rails关联扩展抛出未定义的方法

时间:2016-02-06 13:58:47

标签: ruby-on-rails ruby activerecord

我试图创建一个Active Record匿名关联扩展,文档解释为here。而且我有这个型号

class Program < ActiveRecord::Base
  has_many :reports do 
    def asdf
      "Hello extension"
    end
  end
end

class Report < ActiveRecord::Base
  belongs_to :program
end

但是当我在rails c控制台上对此进行测试时,我发现了undefined method错误。

Loading development environment (Rails 4.2.5)
2.1.0 :001 > Program.first.reports.asdf
  Program Load (0.3ms)  SELECT  `programs`.* FROM `programs`  ORDER BY `programs`.`id` ASC LIMIT 1
NoMethodError:   Report Load (0.3ms)  SELECT `reports`.* FROM `reports` WHERE `reports`.`program_id` = 1
undefined method `asdf' for #<Report::ActiveRecord_Associations_CollectionProxy:0x000001035e0098>
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/activerecord-4.2.5/lib/active_record/relation/delegation.rb:136:in `method_missing'
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/activerecord-4.2.5/lib/active_record/relation/delegation.rb:99:in `method_missing'
    from (irb):1
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/railties-4.2.5/lib/rails/commands/console.rb:110:in `start'
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/railties-4.2.5/lib/rails/commands/console.rb:9:in `start'
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/mariowise/.rvm/gems/ruby-2.1.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

我没有尝试在许多关联之间共享相同的扩展,只是试图通过匿名模块(块)来完成这项工作。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

这是因为您检索了许多报告并在其上调用了方法 asdf ,而您的方法 asdf 是针对单个报告定义的。

试试这个

  Program.first.reports.first.asdf