【问题标题】:How do I set up custom ActiveRecord association?如何设置自定义 ActiveRecord 关联?
【发布时间】:2026-01-13 14:15:02
【问题描述】:

我需要连接三个模型。

这些模型是:

Container

Item

ItemProperty

我不知道如何找到属于容器的所有项目。每个 Item 都有许多与之关联的 ItemProperties。在这些 Item 属性中,至少有一个具有以下数据。

#   id: 2164
#   property_key: container_id
#   property_value_integer: 1
#   world_item_id: 438
#   property_value_type: integer
#   is_active: 1

如何根据包含的 ItemProperty 找到哪些项目属于容器

property_key: container_id
property_value_integer: 1 (this is the id of the container)

请帮忙,谢谢!

当前协会:

class ItemProperty < ApplicationRecord
  belongs_to :item, :class_name => 'Item', :foreign_key => 'item_id'
end

class Item < ApplicationRecord
  has_many :item_properties
end

【问题讨论】:

  • 我不明白你的问题。您能否清楚地说明如何为每个模型设置外键?另外,每个项目属性都有一个 property_value_integer,还是只有一些?
  • 您的 ItemProperty 似乎没有 item_id 属性。但是有一个world_item_id 属性。我很困惑...
  • 您尝试了哪些代码,显示的错误是什么?

标签: ruby-on-rails ruby activerecord ruby-on-rails-5


【解决方案1】:

试试这个。这里的关键是 has_many xxx, :through=> yyy

class Container < ApplicationRecord
 belongs_to :item #or has_many :items depending on your needs
 has_many :item_properties, :through => :items
end 

class Item < ApplicationRecord
  has_many :item_properties
end  

class ItemProperty < ApplicationRecord
  belongs_to :item, :class_name => 'Item', :foreign_key => 'item_id'
end

然后您可以查询所选项目属性的容器。希望对您有所帮助。

【讨论】: