How do I set up these ActiveRecord relationships properly?
I ha开发者_StackOverflow中文版ve a problem understanding how to set up the ActiveRecord relationships correctly for the following scenarios...
Now I have this tree of products:
Product
-> ProductTypes
-> Subtypes
-> Subtypes
-> ...
-> Subtypes
-> ProductItem
where Product is:
class Product < ActiveRecord::Base
has_many :product_types
has_one :product_item, :foreign_key => "product_id"
end
ProductType and Subtype is:
class ProductType < ActiveRecord::Base
belongs_to :product
belongs_to :parent_type, :class_name => "ProductType"
has_many :subtypes, :class_name => "ProductType", :foreign_key => "parent_type_id"
has_one :product_item
end
and ProductItem is:
class ProductItem < ActiveRecord::Base
belongs_to :product_type
belongs_to :product
end
But I also want the tree to allow Product
to have ProductItem
only (i.e. without subtypes), such as:
Product
-> ProductItem
How can I go about setting these up to achieve these requirements? Thanks!
This depends on what ProductType is. If it is a categorization, then it might make sense to have that association of has_many :product_types. If what you really want are actual different types of Products, then I would use STI to make your life a little simpler. Plus I would simplify product_item to just item, unless you have good reason to.
http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/
STI Way Add a migration to your Products table to add a type column:
add_column :products, :type, :string
Then change your models to be like the following:
product.rb
class Product < ActiveRecord::Base
has_one :item
end
type_1.rb
class Type1 < Product
end
type_2.rb
class Type2 < Product
end
etc.
For your subtypes I would do the same thing (taking type1 for example):
subtype_1.rb
class Subtype1 < Type1
end
So now all your different types and subtypes have an item associated to them. Your item now just has an association to product and you're done.
item.rb
class Item < ActiveRecord::Base
belongs_to :product
end
If this isn't what you want then I'll be happy to change my answer if you provide more clarity.
精彩评论