【发布时间】:2014-09-10 23:51:54
【问题描述】:
我正在实现一个 Rails 4 应用程序,它具有反射多对多关联来表示一些 MailChimp 和 HelpScout API 参数。
其中一些参数有子参数。因此,这些子参数具有父参数(否则它们不可能是子参数,对吧?!;D)。
为了实现自反关联,创建了以下两个表
create_table "api_params", force: true do |t|
t.string "name"
t.string "description"
t.string "type"
t.boolean "required"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "nested_params", force: true do |t|
t.integer "parent_param_id"
t.integer "child_param_id"
t.boolean "required"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "nested_params", ["child_param_id"], name: "index_nested_params_on_child_param_id"
add_index "nested_params", ["parent_param_id"], name: "index_nested_params_on_parent_param_id"
我想要的是两种方法。一种用于检索数据库记录的父项,另一种用于检索其子项。下面我给大家举个例子。
apiParam = ApiParam.first # retrieving any database record
apiParam.parent_params
# => returns a set of apiParam's parents
apiParam.child_params
# => returns a set of apiParam's children
我整天都在阅读有关关联的信息,但示例总是相同的。我的意思是,总是有一个类你定义了一个 has_many through 和另一个类你定义了一个 belongs_to 但这还不足以满足我的需要。
提前致谢。感谢您的任何帮助。
【问题讨论】:
-
您能解释一下为什么
has_many :through不起作用吗?乍一看好像has_many :children, through: :nested_params -
@txdavidtx 问题是我需要一个双向的关系,这样我才能获得 parent_params 和 child_params。另一个问题是我没有为 nested_params 表的外键使用默认名称,这让一切都变得有些困难
标签: ruby-on-rails-4 many-to-many rails-activerecord model-associations