Skip to content

Instantly share code, notes, and snippets.

@pyk
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pyk/9015739 to your computer and use it in GitHub Desktop.
Save pyk/9015739 to your computer and use it in GitHub Desktop.

punya satu kategori:

shoes = Category.create(name: "shoes")

terus ada beberapa produk yang dimasukkan ke kategori shoes:

sepatu_a = Product.create(name: "sepatu a")
sepatu_b = Product.create(name: "sepatu b")

sepatu_a.product_categories.create(category: shoes)
sepatu_b.product_categories.create(category: shoes)

sepatu_a.categories # => ...name: "shoes", ...
sepatu_b.categories # => ...name: "shoes", ...

nah sekarang gimana cara mencari semua produk yang berkategori shoes?

shoes.products # => ..., name: "sepatu a" .., ... name: "sepatu b", ...
class Product < ActiveRecord::Base
has_many :categories, through: :product_categories
has_many :product_categories
end
class ProductCategory < ActiveRecord::Base
belongs_to :product
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :products, through: :product_categories
has_many :product_categories
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment