如何将布尔值存储在JSONB列中
我从我的表单中获取一个复选框值,如下所示
<%= 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]])
,它存储在数据库中,如下所示
{
"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 值存储在字符串 格式,但我想将其存储为 布尔值。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
JSONB
中不可能将其保存为DB中的“字符串”。您可以创建自己的序列化器,以根据需要解析JSONB,或者只有布尔部分对您来说很重要,则可以在模型中创建一种方法,
因此代码中的任何地方都可以通过调用此方法来获得真正的布尔值。
想象一下,您有以下记录
,并且在代码中的某个地方您需要检查
forgive_option
ismust_popular
,因为在我们的上一个记录
bucced_options
as中must_popular
将设置为'true'
我们的模型方法buckit_mast_popular
将施放此'true''
以返回布尔值true因此,我们的节目将渲染
most_popular
template这是一篇有趣的博客文章,内容涉及带有Rails的JSONB
It's not possible in
jsonb
it will be always save as a "string" in the DB.You can create your own serializer to parse the jsonb as you want or if only the boolean part matter for you, you can create a method in your model like this
So anywhere in your code you can get a real boolean value by calling this method.
Imagine you have the following record
And somewhere in your code you need to check if
budget_option
ismost_popular
Since in our last record
budget_options
asmost_popular
set as'true'
our model methodbudget_most_popular
will cast this'true'
to return a booleantrue
so our show will render themost_popular
templateHere is an interesting blog article about the jsonb with Rails