【问题标题】:has_many through belongs_to with a has_manyhas_many 到 belongs_to 和 has_many
【发布时间】:2016-04-04 12:09:44
【问题描述】:

这就是我想要达到的目标:

class Foo
  belongs_to :bar
  has_many :foos, trough: :bar, class_name: 'Foo'
end

class Bar
  has_many :Foo
end

如果没有可连接件,这可能吗?通过 has_many 尝试了 class_name 和 source 选项的不同组合,但到目前为止没有成功。要么我被困在一个找不到的源上——即使它提供了,或者我最终陷入了一个神秘的No block given 错误。甚至尝试从:bar 委托给:foo

主要目标:Foo.first.foos 作为关系

如果可能的话,也许有人可以启发我,如果是的话:如何?

最好的问候

【问题讨论】:

  • 你需要这样的记录:Class_A.first.Class_B.Class_As ??
  • 你想解决什么问题?
  • 我不知道你为什么需要这个,你可以通过 a.b.a 轻松获取这些详细信息,或者只是创建一个范围或方法
  • 抱歉回复晚了。它必须是一个关系,因为我们在通用生成的自定义 json 中使用它,该 json 由一些 angularjs 应用程序解析。所以不幸的是它必须是这样的。所以它需要解决像这样的 Foo.first.foos.

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


【解决方案1】:

source 工作正常。

class Foo < ActiveRecord::Base
  belongs_to :bar
  has_many :placeholder, through: :bar, source: :foo
end

class Bar < ActiveRecord::Base
  has_many :foo
end

您使用哪个 Rails 版本?

【讨论】:

  • 用更清晰的类名更新了我的问题。不幸的是,它不适用于源代码,它抱怨No block given
猜你喜欢
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 2020-04-07
  • 2014-10-23
相关资源
最近更新 更多