【发布时间】:2020-03-07 00:47:57
【问题描述】:
考虑到可以学习各种事物的学生,我将它们存储在引用研究表的 jsonb 列中。为研究编制索引并不重要(目前),我更愿意避免使用关系表。
因此:add_column :students, :studies, :jsonb, default: []
以我的简单形式(苗条):
= simple_form_for @student do |f|
= f.input :studies, as: :check_boxes, collection: Study.all, label_method: :name
考虑到它的简洁性和简单性,这非常棒效果很好。除了一个小细节:表单不会检查以前保存的研究,因为它们的 ID 作为字符串存储在 jsonb 数组 ["", "2", "12"] 中,并且表单显然需要整数。
我求助于在 Student 模型中添加了一个研究的值函数,但这似乎太过分了(还有 .reject(&:zero?) 来删除空数组值):
def studies=(array)
# transform strings to integers and remove leading empty value
super(array.map(&:to_i).reject(&:zero?))
end
有没有更好的办法?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 simple-form jsonb has-many