Eine Möglichkeit Hat-Many-Through
-
27-09-2019 - |
Frage
Ich habe eine Kategorie, eine Unterkategorie und ein Produktmodell.
ich habe:
Category has_many Subcategories
Subcategory has_many Products
Subcategory belongs_to Category
Product belongs_to Subcategory
Gibt es eine Möglichkeit, etwas zu haben, wie
Category has_many Projects through Subcategories
Die ‚normale‘ Schienen nicht so funktionieren würde, weil „Untergruppe“ nicht gehört nicht zum Produkt, so Produkt keinen subcategory_id Feld hat. Stattdessen muss ich die Abfrage so etwas wie
seinSELECT * FROM products WHERE id IN category.subcategory_ids
Gibt es eine Möglichkeit, das zu tun?
Danke,
Nicolás Hock Isaza
Lösung
Wenn Sie dies tun die ‚normale‘ Ruby on Rails Art und Weise, die Datenbank, die Sie beschrieben würde wie folgt aussehen. Wenn Ihre Datenbank wie diese nicht strukturiert ist, empfiehlt das Lesen ich mehr darüber, wie Verbände für on Rails in Ruby getan werden, weil dies der richtige Weg ist (und Sie sollten t.references :category
in Ihrer Migration verwenden, da es entworfen wurde, um es einfach nicht Chaos Ihre Referenzen nach oben).
+----------------+ +----------------+ +----------------+
| categories | | subcategories | | products |
+----------------+ +----------------+ +----------------+
| id | | id | | id |
| ... | | category_id | | subcategory_id |
| | | ... | | ... |
+----------------+ +----------------+ +----------------+
Mit diesem als Ihre Datenbankstruktur, die has_many :products, :through => subcategories
arbeitet für das Category
Modell.
class Category < ActiveRecord::Base
has_many :subcategories
has_many :products, :through => :subcategories
end
Subcategory.rb
class Subcategory < ActiveRecord::Base
belongs_to :category
has_many :products
end
Product.rb
class Product < ActiveRecord::Base
belongs_to :subcategory
has_one :category, :through => :subcategory # don't need this, but it does work
end
Ruby-Skript \ Konsole
>> c = Category.create
=> #<Category id: 1, ...>
>> c.subcategories.create
=> #<Subcategory id: 1, category_id: 1, ...>
>> p = s.products.create
=> #<Product id: 1, subcategory_id: 1, ...>
>> c.products
=> [#<Product id: 1, subcategory_id: 1, ...>]
>> p.category # if you have the has_one assocation
=> #<Category id: 1, ...>