PostgresqlJSONB嵌套形式ruby on rails



我将product作为活动记录表,将option_type作为活动模型。选项类型是如下所示的对象数组,

[
{name: 'color', values: ['red', 'blue']},
{name: 'size', values: ['small', 'medium']}
]

class OptionType
include ActiveModel::Model
attr_accessor :name, :values, :default_value
def initialize(**attrs)
attrs.each do |attr, value|
send("#{attr}=", value)
end
end
def attributes
[:name, :values, :default_value].inject({}) do |hash, attr|
hash[attr] = send(attr)
hash
end
end
class ArraySerializer
class << self
def load(arr)
arr.map do |item|
OptionType.new(item)
end
end
def dump(arr)
arr.map(&:attributes)
end
end
end
end

我想为option_types设计一个嵌套表单的form_for,这样用户就可以添加各种选项名称及其值。怎么做?

参考链接如下,

使用RubyOnRails 验证jsonb对象数组中的对象

我知道这不是你所希望的答案,但与其把所有的东西都扔进一个JSONB列,并希望得到最好的结果,你应该尽可能用关系的方式对它进行建模:

class Product < ApplicationRecord
has_many :options
has_many :product_options, through: :options
end
# rails g model option name:string product:belongs_to
class Option < ApplicationRecord
belongs_to :product
has_many :product_options
end
# rails g model product_option option:belongs_to name:string ean:string
class ProductOption < ApplicationRecord
belongs_to :option 
has_one :product, through: :options
end

如果您的数据实际上具有足够的结构,可以编写引用其属性的代码,那么JSON列就不是正确的答案。JSON/数组也不是设置关联的正确答案。

这使您可以使用外键来维护引用的完整性,并具有某种程度上合理的模式和查询,而不仅仅是处理完全无结构的混乱。如果你必须处理一个可以有不同类型的属性,比如一个可以是字符串、布尔值或数字的选项,你可以使用JSON列来存储值,以在一定程度上减轻旧EAV模式的缺点。

根据您的需求,创建产品的变体可以通过单独的表单、嵌套属性或AJAX来完成。

最新更新