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

wbgh16ku  于 2023-11-20  发布在  Ruby
关注(0)|答案(1)|浏览(126)

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

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

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

xxe27gdn

xxe27gdn1#

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

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

字符串

相关问题