2017-12-17 23 views
-2

私は接続する必要がある3つのモデルがあります。カスタムActiveRecordの関連付けを設定するにはどうすればよいですか?

これらのモデルは、以下のとおりです。

Container 

Item 

ItemProperty 

私はコンテナに属するすべてのアイテムを見つける方法を見つけ出すことはできません。各Itemには、それに関連付けられた多くのItemPropertiesがあります。これらのItemプロパティのうち、少なくとも1つは、次のデータを持つプロパティを持ちます。

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

どのように私はあなたに感謝し、助けてください

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

が含まれているItemPropertyに基づいてコンテナに属するアイテムを見つけるでしょう!

現在の協会:

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

class Item < ApplicationRecord 
    has_many :item_properties 
end 
+3

私はあなたの質問を理解していません。それぞれのモデルにどのように外部キーが設定されているかを明確に説明できますか?また、すべてのアイテムプロパティはproperty_value_integerを持っていますか? – sakurashinken

+1

ItemPropertyに 'item_id'属性がないようです。しかし、 'world_item_id'属性があります。私は混乱しています... – spickermann

+0

あなたはどのようなコードを試しましたか?それが示したエラーは何ですか? –

答えて

1

はこれを試してみてください。鍵はここに奪うにhas_many XXX、次のとおりです。=> 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 

を通じてあなたは、選択した項目のプロパティのコンテナ(複数可)を照会することができます。それが役に立てば幸い。

関連する問題