我有一個item
模型,其belongs_to
一個product
模型。 每個product
has_and_belongs_to_many
specification
型號:has_and_belongs_to_many:如何獲得正確的關係? (JSON輸出)
products
和
specifications
之間
class Product < ActiveRecord::Base
has_many :items
has_and_belongs_to_many :specifications
end
關係保存內products_specifications
JOIN表:
create_table "products_specifications", id: false, force: :cascade do |t|
t.integer "product_id"
t.integer "specification_id"
end
每個specification
has_and_belongs_to_many
tags
:
class Specification < ActiveRecord::Base
# Product Specifications (e.g. Color, Weight, Size, Brand, Product-Type)
has_and_belongs_to_many :products
has_and_belongs_to_many :tags # Tags = Spec Detail (e.g. blue, 100 gramm, 5x5x2.5 cm, Apple, Smartphone)
end
JOIN表specifications_tags
:
create_table "specifications_tags", id: false, force: :cascade do |t|
t.integer "specification_id"
t.integer "tag_id"
end
同時,各tag
has_and_belongs_to_many
specifications
:
class Tag < ActiveRecord::Base
# Product Specifications Tag/Details (e.g. blue, 100 gramm, 5x5x2.5 cm, Apple, Smartphone)
has_and_belongs_to_many :specifications
end
我嘗試輸出項目的產品與JOIN表相關的規範和JOIN表格相關標籤如下:
def show
item = Item.find(params[:id])
render json: item.to_json(include: {
product: {include: {specifications: {include: {tags: {}}}}}
})
end
這確實輸出正確的產品型號,但它包含的而不是隻有那些相關的所有規格和數據庫中的所有標籤。目前看起來簡化了這樣的錯誤 JSON輸出(用於item
屬於「蘋果iPhone 6智能手機」 product
):
"item":{"id":1,"product":
{"id":1,"name":"Apple iPhone 6 Smartphone","specifications":
[
{"id":1,"name":"Product Type","tags":
[
{"id":1,"name":"Smartphone"},
{"id":1,"name":"Smartphone"}
]
},
{"id":2,"name":"Brand","tags":
[
{"id":2,"name":"Apple"},
{"id":4,"name":"Samsung"}
]
},
{"id":3,"name":"Model","tags":
[
{"id":3,"name":"iPhone 6"},
{"id":5,"name":"Galaxy A5"}
]
}
]
}
}
目前我只有兩個products
數據庫中的:「蘋果iPhone 6智能手機」和「三星Galaxy A5智能手機」。您可以看到它輸出所有產品的規格和標籤,而不是僅相關的has_and_belongs_to_many
。該正確 JSON輸出爲item
有關「蘋果iPhone 6智能手機」 product
看起來像這樣的:
"item":{"id":1,"product":
{"id":1,"name":"Apple iPhone 6 Smartphone","specifications":
[
{"id":1,"name":"Product Type","tags":
[
{"id":1,"name":"Smartphone"}
]
},
{"id":2,"name":"Brand","tags":
[
{"id":2,"name":"Apple"}
]
},
{"id":3,"name":"Model","tags":
[
{"id":3,"name":"iPhone 6"}
]
}
]
}
}
編輯:
問題無關與JSON是如何輸出。真正的問題是:
我該如何正確關聯的標籤各自的產品的各自的規範?
?你有沒有嘗試過使用jbuilder? – kjmagic13
Rails 4.2.3,不,我還沒有嘗試過jbuilder,但我剛剛看到gem已經安裝在我的項目中。我將如何與jbuilder做到這一點? –
我已經更新了我的答案,讓我知道如果這有效。 – kjmagic13