【问题标题】:nested has_many through associations not working通过关联嵌套的 has_many 不起作用
【发布时间】:2012-08-20 16:09:48
【问题描述】:

运行 Rails 3.2.1。如文档 (http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association) 所示,通过关联尝试应该是简单的嵌套 has_many:

class Company < ActiveRecord::Base
  has_many :locations, :dependent => :destroy
  has_many :assets,  :through => :locations
  has_many :components,  :through => :assets
end

class Location < ActiveRecord::Base
  belongs_to :company
  has_many :assets
  has_many :components, :through => :assets
end

class Asset < ActiveRecord::Base
  belongs_to :location
  has_many :components
end

class Component < ActiveRecord::Base
  belongs_to :asset
end

在控制台中Company.find(2)Company.find(2).locations 一样工作正常,但不是Company.find(2).assetsCompany.find(2).components。我明白了:

1.9.3p0 :071 > Company.find(2).assets
  Company Load (0.8ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 ORDER BY name ASC LIMIT 1  [["id", 2]]
NoMethodError: undefined method `assets' for #<Company:0x007f939d714318>

我似乎在这里遗漏了一些东西。我嵌套了一层更深,但根据文档,这应该没问题。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3.2 has-many-through


    【解决方案1】:

    哇……快把我逼疯了。希望我能帮助别人。搜索了控制台错误消息,只需要重新加载控制台... D'oh!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多