我是 Rails 世界的新手,我的任务是创建一个在线商店。
但是我目前在设置数据库关系时遇到问题。我有 product、dimension 和 shipping 类。产品可以有多个尺寸,具体取决于客户选择的产品变体。产品的尺寸可以决定运费多少,但是每个尺寸也会提供多种运输选项。这是我当前的设置:
Product.rb
class Product < ActiveRecord::Base
attr_accessible :title, :description, :image_url, :price, :category_id, :weighting, :stock
has_many :dimensions
end
维度.rb
class Weight < ActiveRecord::Base
attr_accessible :product_id, :size, :weight
has_and_belongs_to :shippings
belongs_to :product
end
Shipping.rb
class Shipping < ActiveRecord::Base
attr_accessible :description, :insurance, :name, :price, :size_id, :weight_id
has_and_belongs_to :dimensions
end
关于这是否是设置此数据库关系的最佳方式,有人能给我一些建议吗?如果不是,什么是更优化的解决方案?
有人告诉我要利用 has_many :through,但我不确定如何最好地实现它。
谢谢
最佳答案
通常 has_and_belongs_to_many
和 has_many :through
之间的决定因素是你是否认为你永远需要 have 关系对象(那个会绑定(bind) has_many :through
together) 和它自己的属性。
对我来说,我很少会像这样过度做事,所以我总是使用 has_many :through
,如果我不向它添加属性,那就这样吧。它为我提供了一个带有关联名称的模型,我可以验证该关联、获取回调等...
Ruby on Rails Guide两者之间有很好的比较。
此外,如果您正在制作 RoR 商店,您是否看过 Spree ?
关于ruby-on-rails - Ruby on Rails 数据库关系结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18323418/