I'm fairly new to the rails world and I've been tasked with making an online store.
However I am currently having trouble setting up the database relationships. I have product , dimension and shipping classes. A product can have several dimensions, depending on what product variant the customer chooses. The dimensions of the product can dictate how much the shipping will cost, however there will also be several shipping options on offer per dimensions. Here is my current setup:
Product.rb
class Product < ActiveRecord::Base
attr_accessible :title, :description, :image_url, :price, :category_id, :weighting, :stock
has_many :dimensions
end
Dimensions.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
Could anyone give me some advice as to whether this is the best way to setup this database relation? And if not, what would be a more optimum solution?
I've been told to utilise has_many :through , however I'm not sure how best to implement this.
Thanks
Typically the deciding factor between has_and_belongs_to_many
and has_many :through
is whether you think you'll ever need the have the relation object (the one that would tie a has_many :through
together) with attributes of its own.
For me, I rarely skimp on over-doing things like this, so I always use has_many :through
, and if I don't add attributes to it, so be it. It gives me a model with a useful name for the association, I can validate that association, get callbacks, etc...
The Ruby on Rails Guide has a pretty good comparison between the two.
Also, if you're making a RoR store, have you looked at Spree ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.