I love modularity in software, and create models accordingly. I think you'll benefit from this idea, so I'll explain it for you:
Models
I like to keep models to make models extensible - so you can add 1,000,000's of items, and still have it work in the right way.
To do this, we have "silo" databases (I'm not sure if this is the right terminology), and then have "reference" models around it.
The "silo" database / model basically stores static data (such as products
or users
). Reference database / models basically give the silo
databases more scope - such as adding options
to products
or a profile
for users
.
In your case, I would definitely do this:
#app/models/product.rb
Class Product < ActiveRecord::Base
has_many :options, as: :optable do
def colours
where name: "colour"
end
end
end
#app/models/option.rb
Class Options < ActiveRecord::Base
belongs_to :optable, polymorphic: true
end
Schemas:
#products
id | name | SKU | stock | etc | etc | created_at | updated_at
#options
id | optable_type | optable_id | name | value | created_at | updated_at
--
Associations
This is a polymorphic association (so you can use the options
model with other unrelated models):
This means you'll be able to call:
@product = Product.find params[:id]
@product.options #-> returns all `Option` records for `product` (`price`, `size`, `etc`)
If you set it up right, you should be able to do this:
#config/routes.rb
resources :products, only: :show #-> domain.com/products/14
#app/controllers/products_controller.rb
class ProductsController < ActiveRecord::Base
def show
@product = Product.find params[:id]
end
end
#app/views/products/show.html.erb
<%= @product.name %>
<% @product.options.each do |option| %>
<%= option.size %>
<%= option.price %>
<%= option.colour %>
<% end %>
If you wanted to call a product
's colour
options, you could then do:
@product = Product.find params[:id]
@product.options.colours #-> will output all colours for the product
Caveats
One of the major caveats with my code is the options
I've provided is not structured in any way. If you wanted to have a particular set
of options for a product (like having size
, colour
, quantity
for a particular product, you may wish to use a self-referential
association in your Option
model, which I can do if you want
Current model schema
is perfect.Go on with it. – Montes