Rails - 多种价格类型的产品数据库模型

Rails - product database model for multiple price types

我正在寻找有关如何处理此问题的建议:

products 多个价格(例如:婴儿:5 欧元,儿童:10 欧元,成人:15 欧元)。

create_table "products", force: :cascade do |t|
  ...
  t.integer "adult_price_cents"
  t.integer "child_price_cents"
  t.integer "infant_price_cents"
  ...
end

现在,我希望某些产品具有 单一价格(例如:45 欧元)(所以没有 多个价格以上)

提前感谢您的宝贵时间和帮助!

如果一个product可能有一个或多个price,最好将价格分开为一个型号two-column是price和[=13] =] with using enumerize ,关联产品型号,一个产品可以有一个或多个价格,我觉得还是管理或者改后者比较好。

您将太多东西塞进了一个模型/table。最好设置一个连接 table 而不是随着复杂性的增加而增加列数。

class Product < ApplicationRecord
  has_many :variants
end

# rails g model variant name:string price:decimal product:belongs_to
class Variant < ApplicationRecord
  belongs_to :product
end

这避免了在 table 中创建一堆主要包含空值的列。

然后您可以检查产品是否有变体,否则使用基本价格:

<h1><%= @product.name %></h1>
<% if @product.variants.any? %>
  <table>
    <tr>
      <th>Name</th>
      <th>Price</th>
    </tr>
    <% @product.variants.each do |v| %>
    <tr>
      <td><%= v.name %></td>
      <td><%= v.price %></td>
    </tr>
    <% end %>
  </table>
<% else %>
  <h2><%= @product.price %></h2>
<% end %>