How to add a size attribute to a product, following the "Build a Store With a Payment Gateway in Rails" tutorial?


#1

Hello,

I am working my way through the “Build a Store With a Payment Gateway in Rails”, and noticed there is no size attribute for product contained in the store. I am hoping to implement a size attribute for a product because the items I plan on selling through my online store are t-shirts (which come in various sizes).

If anyone has any suggestions for how I can accomplish this I would be extremely grateful. Thanks for reading, and have a great day.


#2

Hi Chris, thanks for posting your question here in the forums.

Your requirement has a lot of potential indeed. Given your scenario, off the top of my head, I would do something in these terms.

Create a Size model, which could perfectly be seeded with something like rake db:seed. The model would have a single name attribute. That way you could have Extra Small, Small, Medium, Large, Extra Large and so on, as long a list as you need. An abbreviation attribute can be added to the model if you feel like it.

The next step would be to have a connection between the Product and the Size. The best way to achieve this is through a has_many :through relationship. You would need a third model, perhaps called ProductSize. It would be generated like this:

$ rails generate model product_size product_id:references size_id:references

This would generate the model and migration files.

The last thing to consider would be to adjust the first two main models to establish the correct relationships:

# app/models/product.rb
class Product < ActiveRecord::Base
  # omitted code..
  has_many :sizes, through: :product_sizes
end

# app/models/size.rb
class Product < ActiveRecord::Base
  # omitted code..
  has_many :products, through: :product_sizes
end

This is just the bootstrap of the entire process. You would then need to proceed with complementing the appropriate pages to reflect the change, as well as the cart information and so on.

Hope this helps!

José


#3

@josemota

I think you made a typo in your explanation. You have #app/models/size.rb but you wrote out class Product twice.


#4

You’re absolutely right. Thanks for letting everybody know!