我正在创建一个电子商务网站,我有一个'尺寸'下拉,供客户选择他们的尺寸。我想要的是下拉到只显示数据库中保存的'stock'值可用的显示大小。
有没有人有这方面的经验或有任何见解?
架构中的尺寸表
create_table "sizes", force: true do |t|
t.integer "product_id"
t.integer "stock"
t.string "size"
t.datetime "created_at"
t.datetime "updated_at"
end
Size.rb
class Size < ActiveRecord::Base
belongs_to :product
end
Order_Product.rb
class OrderProduct < ActiveRecord::Base
belongs_to :order
belongs_to :product
belongs_to :size
end
Product.rb
class Product < ActiveRecord::Base
has_many :order_products
has_many :orders, through: :order_products
has_many :sizes
end
产品/ show.html.erb
<%= simple_form_for :basket, url: product_basket_path(@product), remote: true do |f| %>
<%= f.input :quantity, as: :select, collection: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], selected: 1, required: false %>
<%= f.input :size, as: :select, collection: @product.sizes, selected: 0, required: false %>
<%= f.button :submit, "Add to basket" %>
<% end %>
非常感谢!
答案 0 :(得分:3)
向尺寸模型添加范围,并使用此范围填充选择字段。
范围:
class Size < ActiveRecord::Base
belongs_to :product
scope :in_stock, where('stock > 0')
end
选择字段:
<%= f.input :size, as: :select, collection: @product.sizes.in_stock, selected: 0, required: false %>
在视图中使用范围而不是过滤允许您在其他地方重用in_stock范围,并执行SQL查询,而不是加载所有记录并迭代它们。
答案 1 :(得分:1)
我希望我明白你想做什么;您应该可以使用pluck
选择所有可用的尺寸值,如下所示:
@product.sizes.where('stock >= 1').pluck(:size, :id)
编辑:看看Douglas F Shearer的帖子,范围是一个更优雅的解决方案,而不仅仅是将Ruby代码放在你的视图中!
答案 2 :(得分:0)
从@ Douglas的答案中获取灵感,我发现以下内容可行。
<强> Product.rb 强>
class Product < ActiveRecord::Base
has_many :order_products
has_many :orders, through: :order_products
has_many :sizes
def in_stock
self.sizes.where('stock > 0')
end
end
<强>产品/ show.html.erb 强>
<%= f.input :size, as: :select, collection: @product.in_stock, selected: 0, required: false %>
感谢您的帮助!