我从表单中得到一个复选框值,如下所示
<%= f.label 'Most Popular', class: "form-label" %>
                    <%= check_box_tag "price_template[preferences][pcb_budget_options][][most_popular]",
                                        true,
                                        f.object.preferences.dig("pcb_budget_options", index, "most_popular") %>我允许的是这样的
params.require(:price_template).permit(:currency_id,
                                         :program_id,
                                         :active,
                                         :default,
                                         country_ids: [],
                                         preferences: [budget_options:     [:amount, :most_popular, :text],
                                                       pcb_budget_options: [:amount, :most_popular]])它像这样存储在DB中
   {
  "budget_options"=>[
    {"amount"=>"1.0", "text"=>"budget options"},
    {"amount"=>"2.0", "most_popular"=>"true", "text"=>"budget options"},
    {"amount"=>"3.0", "text"=>"budget options"}
  ],
  "pcb_budget_options"=>[
    {"amount"=>"1.0"},
    {"amount"=>"0.0"},
    {"amount"=>"-1.0", "most_popular"=>"true"}
  ]
}但是most_popular值存储在这里是string格式,但我想将其存储为布尔。
发布于 2022-04-08 10:03:12
这在jsonb中是不可能的,它将始终保存为DB中的“字符串”。
您可以根据需要创建自己的序列化程序来解析jsonb,或者,如果只需要布尔部件,则可以在模型中创建如下方法
class Mymodel
  def budget_most_popular
    ActiveRecord::Type::Boolean.new.cast(preferences["budget_options"]["most_popular"])
  end
  def pcb_budget_most_popular
    ActiveRecord::Type::Boolean.new.cast(preferences["pcb_budget_options"]["most_popular"])
  end
end因此,在代码中的任何地方,您都可以通过调用此方法获得一个真正的布尔值。
假设您有以下记录
$> MyModel.first
<MyModel:0x029I23EZ
id: 1,
name: "foo",
preferences: {
  "budget_options" => 
    [ 
      { "amount"=>"10", "most_popular"=>"true", "text"=>"" },
      {"amount"=>"0.0", "text"=>""}, {"amount"=>"0.0", "text"=>""}
    ],
  "pcb_budget_options"=>
    [
      {"amount"=>"20", "most_popular"=>"false"}, {"amount"=>"0.0"},
      {"amount"=>"0.0"}
    ]
}
...在代码中的某个地方,您需要检查budget_option是否为most_popular
class MyModelController
   def show
     @mymodel = MyModel.first
     if @mymodel.budget_most_popular
       render "template/most_popular"
     else
       render "template/less_popular"
     end
   end
end因为在我们最后一次记录budget_options作为most_popular集为'true',我们的模型方法budget_most_popular将转换这个'true'来返回一个布尔true,所以我们的显示将呈现most_popular模板
https://stackoverflow.com/questions/71794593
复制相似问题