Rails:如何清理嵌套对象以保存到 JSONB 列?

Rails: how to sanitize nested object to save to JSONB column?

提问人:t56k 提问时间:11/13/2023 更新时间:11/14/2023 访问量:36

问:

在 Rails 控制器中给定这些强参数:

def user_params
  params.require(:user).permit(details: [{ group: %i[type value] }])
end

如何在数组持久化到 JSONB 列之前对其进行清理?details

Ruby-on-Rails 强参数

评论


答:

1赞 t56k 11/14/2023 #1

我为其他有类似问题的人写了一个解决方案:

include ActionView::Helpers::SanitizeHelper

# ...

private

def sanitize_details
  return unless details

  self.details = details.map do |group|
    sanitized_details = group['group'].map do |detail|
      { type: sanitize_most(detail['type']), value: sanitize_most(detail['value']) }
    end
    { group: sanitized_details }
  end
end

def sanitize_most(field)
  sanitize(field, tags: %w[a b i strong em], attributes: %w[href rel target])
end