I made a simple inventory system, and want to display a selector to choose the size before buying the product. I want the selector to only show the items that are in stock, and not allow the user to choose the ones that aren’t. I made it so that when the product is created, it creates a set of variants, with their name and quantity. So when I create a product, it creates 3 variants named Small, Medium, and Large, each with a qty of 0. I used the ruby console to update the qty of each variant so the below would work:
views/product/show.html.erb
<div class="size"><br/>Size: <%= f.select(:size, options_for_select(@sizes_availiable), :prompt => "Select a size") %></div>
product_controller.rb
def show
@product = Product.find(params[:id])
@sizes_availiable = Product.build_size_enum( @product.id )
end
Product.rd
def self.build_size_enum(product_id)
p = Product.find(product_id)
a = []
p.variants.each do |var|
unless var.qty = 0
a << var.name
end
end
a
end
However, the options are empty (with only the option “Select a size”). If I remove the unless statement (which defeats the purpose) from Product.rb so the method looks like below, the list populated with small medium and large:
Product.rd
def self.build_size_enum(product_id)
p = Product.find(product_id)
a = []
p.variants.each do |var|
a << var.name
end
a
end
Any ideas on why the unless statement is causing a problem?
You are using
=instead of==.var.qty = 0will always test as “true” in Ruby, with the unfortunate side effect of wiping out the data you are trying to test. Change that tovar.qty == 0and you should be fine.