如何设置自定义ActiveRecord关联?

问题描述 投票:-2回答:1

我有三个需要连接的模型。

这些模型是:

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
ruby-on-rails ruby activerecord ruby-on-rails-5
1个回答
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

然后,您可以查询所选项属性的容器。希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.