model association for a e-store app
I'm developing an e-store app using ruby on rails and I'm a bit confused about the model associations. It would help me if someone could give开发者_开发技巧 me an idea about the tables and their associations. Here are the details:
Parent tables: =>Categories, occasions, Hot Deals
Under Categories: =>Men, Women, Kids
Under Men: =>Shirts, Trousers
Under Women: =>Shirts, Trousers, Skirts
Under Kids: =>Shirts, Trousers
Under Occasions =>Ethnic, Party, Travel, Casual, Formal
Under Hot Deals =>Hot Deals Index
And lastly every last sub-table will have product index.
Thank you!
What you would generally do with something like this is build a Taxonomy tree to that would be associated with the products, allowing you to group products together. A many to many relation between Taxonomy and Product let's you associate a product with multiple groups, so a T-Shirt might be under Categories > Men > Shirts as well as Occasion > Casual.
# app/models/taxonomy.rb
class Taxonomy < ActiveRecord::Base
has_many :taxonomies
has_and_belongs_to_many :products
end
# app/models/product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :taxonomies
end
then a migration for the join table between taxonomy/product
rails g migration create_products_taxonomies
and edit it
def change
create_table(:products_taxonomies, :id => false) do |t|
t.references :product
t.references :taxonomy
end
end
From there you would basically create in the database 3 Taxons, 1 for each of your sections, then create the Taxonomy and build out the sub levels. When you create your products, assign the right Taxonomy to the product and your set.
A seed file might look like...
Taxonomy.create!(:name => "Category").tap do |category|
category.taxonomies.create!(:name => "Men").tap do |men|
men.taxonomies.create!(:name => "Shirt")
men.taxonomies.create!(:name => "Trousers")
end
# and so on for each category
end
Then when you create a Product, you can associate it with the Taxonomy and use that Taxonomy to pull up a list of products that are associated with it.
精彩评论