[英]How to insert a hash in an ActiveRecord column on Ruby On Rails
My Dev Env我的开发环境
Rails 6.0.3.4导轨 6.0.3.4
sqlite3 sqlite3
ruby 2.6.3 ruby 2.6.3
and a RoR n00B和一个RoR n00B
My Model Goal
has a few attributes like title
, created_on
etc. Essentially standard types like text,date,boolean
etc.我的 Model Goal
有一些属性,如title
、 created_on
等。基本上是标准类型,如text,date,boolean
等。
I have validations in place,I am able to read from DB, post from form etc.CRUD operations are fine.So far so good.我已经进行了验证,我可以从 DB 中读取,从表单等中发布。CRUD 操作很好。到目前为止一切都很好。
Now I want to add a new column called tracking_data
which will be a type of hash like this现在我想添加一个名为tracking_data
的新列,它将是 hash 的类型,如下所示
{
21-12-2020:true,
22-12-2020:false,
etc
etc
}
The idea is goal will have a column called tracking_data
like above which is essentially a hash of { date:bool }
.这个想法是目标将有一个名为tracking_data
的列,如上所示,它本质上是{ date:bool }
的 hash 。 It simply records if on a particular date(key), the user has worked on the goal.True or false(value).它仅记录用户是否在特定日期(键)上完成了目标。真或假(值)。 Essentially the user will select a date, check/uncheck the status for the date in the form.本质上,用户将 select 一个日期,选中/取消选中表单中日期的状态。 I am using sqlite3
currently.我目前正在使用sqlite3
。 As mentioned here from the official docs https://api.rubyonrails.org/classes/ActiveRecord/Store.html , I am trying to implement the same.正如官方文档https://api.rubyonrails.org/classes/ActiveRecord/Store.html中提到的,我正在尝试实现相同的功能。 What I have done so far, and which obviously is not correct
is define something like到目前为止我所做which obviously is not correct
的是定义类似
store:tracking_data, accessors: [:date, :status]
on the goal.rb
model file. store:tracking_data, accessors: [:date, :status]
on the goal.rb
model 文件。 By virtue of the store
wrapper, I get access to the date
and status
accessor methods on goal.凭借store
包装器,我可以访问目标date
和status
访问器方法。 Which I use to read inputs from the form.我用它来读取表单中的输入。 The form code looks like this表单代码如下所示
<%= form.date_field :date %>
<%= form.check_box :status %>
So my query is所以我的查询是
How can I read the date input by the user from the form along with the status and set that as key/value in the tracking_data hash.如何从表单中读取用户输入的日期以及状态,并将其设置为 tracking_data hash 中的键/值。
Basically I should not be passing the :date
attribute in the store
function, because that has to be input by the user.基本上我不应该在store
function 中传递:date
属性,因为它必须由用户输入。
Additional I am using the default Yaml serializer with store
.另外,我正在使用带有store
的默认 Yaml 序列化程序。 Any help is appreciated and please let me know If I can clarify this further.任何帮助表示赞赏,如果我能进一步澄清这一点,请告诉我。
Thank you谢谢
If you define the column data type as jsonb
, you can create or update records with something like如果将列数据类型定义为jsonb
,则可以使用类似的内容创建或更新记录
Goal.create!(tracking_data: { '21-12-2020': true })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.