首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在jsonb列中存储布尔值

如何在jsonb列中存储布尔值
EN

Stack Overflow用户
提问于 2022-04-08 09:23:08
回答 1查看 394关注 0票数 0

我从表单中得到一个复选框值,如下所示

代码语言:javascript
运行
复制
<%= 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") %>

我允许的是这样的

代码语言:javascript
运行
复制
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中

代码语言:javascript
运行
复制
   {
  "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格式,但我想将其存储为布尔

EN

回答 1

Stack Overflow用户

发布于 2022-04-08 10:03:12

这在jsonb中是不可能的,它将始终保存为DB中的“字符串”。

您可以根据需要创建自己的序列化程序来解析jsonb,或者,如果只需要布尔部件,则可以在模型中创建如下方法

代码语言:javascript
运行
复制
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

因此,在代码中的任何地方,您都可以通过调用此方法获得一个真正的布尔值。

假设您有以下记录

代码语言:javascript
运行
复制
$> 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

代码语言:javascript
运行
复制
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模板

这里有一篇有趣的关于带有Rails的jsonb的博客文章。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71794593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档