Rails3中嵌套关联的问题

时间:2010-06-22 20:22:24

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

我在Rails3中遇到了一些关联问题。

我有以下协会

InformationCategory :has_many => Informations :has_many => InformationValues

我能够成功地做到以下几点:

Information.first.information_values
=> [#InformationValue..]

我也可以做到以下几点:

InformationCategory.first.informations
=> [#Information...]

然而,由于某种原因,这失败了:

InformationCategory.first.informations.first.information_values
=> NoMethodError: undefined method `information_values' for #<Information:0x000001053321c8>

为什么我不能在Rails中使用'嵌套关联'?该错误消息明确指出InformationCategory.first.informations.first返回Information

的实例

我做错了吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

您没有在最外层模型上定义所有嵌套后代:每个模型定义它“直接”has_many的内容,或者它所属的模型。因为你的问题是错误的,所以我只能猜测,而不是更具体地看到你的模型应该如何相关。

这可能是一个开始:

class InformationCategory < ActiveRecord::Base
  has_many :informations
end

class Information < ActiveRecord::Base
  belongs_to :information_category
  has_many :information_values
end

class InformationValue < ActiveRecord::Base
  belongs_to :information
end

但是,您可能正在尝试has_many :through,但我无法从您的问题中说出来。

相关问题