【问题标题】:Confusion with has_many :through与 has_many 混淆:通过
【发布时间】:2016-12-05 08:49:06
【问题描述】:

我对为我正在使用的数据集实现 has_many :through 完全感到困惑。所以我有两个表 - scheme_masterscheme_detail

scheme_master 有这些字段 - id、scheme_detail_id、primary_scheme_id

scheme_detail 有一个相关字段 - id

scheme_master 中的每个方案都有一个主方案,该方案自引用到 scheme_master 表。例如,方案 1 是方案 1、2、3 的 primary_scheme。

相关代码如下

scheme_master.rb

class SchemeMaster < ActiveRecord::Base
  has_one :scheme_detail
  has_many :child_schemes, class_name: "SchemeMaster", 
    foreign_key: :primary_scheme_id, primary_key: :id
end

scheme_detail.rb

class SchemeDetail < ActiveRecord::Base
  belongs_to :scheme_master
end

我的问题是如何访问我所有子计划的计划详细信息?

目前,

SchemeMaster.find(1).child_schemes

给了我所有的子方案 - 1,2,3,但我想要一个关联来引用 child_schemes 的 scheme_detail。谢谢。

【问题讨论】:

  • 试试has_many :scheme_details, through: :child_schemes
  • 它会抛出堆栈级别太深的错误。 :(

标签: ruby-on-rails ruby associations


【解决方案1】:

首先scheme_masters表有scheme_detail_id,所以你需要改变这个关联

class SchemeMaster < ActiveRecord::Base
  belongs_to :scheme_detail
end

class SchemeDetail < ActiveRecord::Base
  has_one :scheme_master
end

现在,要获取 child_schemes 中的所有 scheme_detail,请执行此操作

scheme_master = SchemeMaster.includes(child_schemes: :scheme_detail).where(id: 1).first

要获取child_schemes 中的scheme_detail,您可以这样做,scheme_master.child_schemes.first.scheme_detail

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多