【问题标题】:Problem with nested associations in Rails3Rails3中嵌套关联的问题
【发布时间】:2010-06-22 20:22:24
【问题描述】:

我在 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 的实例

我是不是做错了什么?

提前致谢!

【问题讨论】:

  • 顺便说一句,如果我在信息对象失败的情况下检查它,它表明没有任何“魔术”关联方法被添加到对象中。
  • 能否请您发布模型中的代码?

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


【解决方案1】:

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

这可能是一个开始:

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,但我无法从您的问题中看出。

【讨论】:

    猜你喜欢
    • 2011-03-18
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多