我在我的rails 7应用程序上使用了@yairEO/tagify.我已经把它弄好了.它将作为有效的JSON保存到数据库中.如果我使用带有3个标记的Tagify提交表单,例如tag1tag2tag3,在我返回到表单进行编辑后,Tagify会将这3个单独的标记组合到一个标记中.

从数据库中:

[
  {
    "value":"tag1"
  },
  {
    "value":"tag2"
  },
  {
    "value":"tag3"
  }
]

来自IRB recipe.tags:

[
  {
    "value"=>"tag1"
  },
  {
    "value"=>"tag2"
  },
  {
    "value"=>"tag3"
  }
]

Before submitting: before

After submitting: after

Things quickly get out of control when adding to the bad response. Before submitting: enter image description here

After submitting: enter image description here

application.js

import Tagify from "@yaireo/tagify"

document.addEventListener('turbo:load', (event) => {
  new Tagify(document.querySelector('#recipe_tags'));
});

recipes_controller.rb

def update
  @recipe.update(tags: JSON.parse(params[:recipe][:tags]))

  if @recipe.update(recipe_params)
    redirect_to @recipe
  else
    render :edit, status: :unprocessable_entity
  end
end
def recipe_params
  params[:recipe][:tags] = JSON.parse(params[:recipe][:tags])
  params.require(:recipe).permit(
    :title, :subtitle, :tags
  )
end

edit.html.erb

<div>
  <%= form.label :tags %><br>
  <%= form.text_field :tags %>
  <% recipe.errors.full_messages_for(:tags).each do |message| %>
    <div><%= message %></div>
  <% end %>
</div>

schema.rb

  create_table "recipes", force: :cascade do |t|
    t.string "title"
    t.string "subtitle"
    t.jsonb "tags", default: {}, null: false
    t.index ["user_id"], name: "index_recipes_on_user_id"
  end

编辑:

从控制器中移除@recipe.update(tags: JSON.parse(params[:recipe][:tags]))params[:recipe][:tags] = JSON.parse(params[:recipe][:tags])会导致正确显示数据.但是,会抛出500错误:

Completed 500 Internal Server Error in 19ms (ActiveRecord: 10.6ms | Allocations: 4899)
NoMethodError (undefined method `join' for "[{\"value\":\"tag1\"},{\"value\":\"tag2\"},{\"value\":\"tag3\"}]":String):

尽管出现500错误,数据仍将保存到数据库中,并在刷新时正确显示.我想现在的问题是,为什么会有500错误,可以做些什么来解决它?

推荐答案

总是那些小而愚蠢的东西被忽视,花了太多的时间才能注意到!

recipes_controllershow方法中使用了meta-tagsRuby ,如下所示: set_meta_tags keywords: @recipe.tags.join(', ') unless @recipe.tags.empty?

这导致了提交表单时的错误,因为用户被重定向到包含此错误代码的show视图.

正如我在原始问题中所描述的,在刷新(edit页)时,一切都按预期工作--这是因为没有调用控制器中的损坏代码.

Json相关问答推荐

当console.log返回TRUE值时,解析的JSON中的字段未定义

序列化从/到空值

在 json 对象中存储多个键:值对

在 postgres 14 中将记录转换为所需的 json 格式

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

如何编写 jolt 规范以将不同的对象转换为数组

用于遮蔽卡的 Jolt 规格

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

MarkLogic REST 资源 API - 仅使用一个 POST 请求修补多个文档

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

PowerShell - JSON/PsCustomObject - 为什么我的数组被扁平化为一个对象?

序列化为json时如何忽略空列表?

使用 Javascript 判断 JSON 对象是否包含值

从多维数组数据生成json字符串

JSON对象中的JavaScript递归搜索

嵌套 JSON:如何向对象添加(推送)新项目?

Swift :将 struct 转换为 JSON?

如何将 mysqli 结果转换为 JSON?

将多个值存储在json中的单个键中

Volley JsonObjectRequest Post 参数不再起作用