我在我的rails 7应用程序上使用了@yairEO/tagify
.我已经把它弄好了.它将作为有效的JSON保存到数据库中.如果我使用带有3个标记的Tagify提交表单,例如tag1
、tag2
、tag3
,在我返回到表单进行编辑后,Tagify会将这3个单独的标记组合到一个标记中.
从数据库中:
[
{
"value":"tag1"
},
{
"value":"tag2"
},
{
"value":"tag3"
}
]
来自IRB recipe.tags
:
[
{
"value"=>"tag1"
},
{
"value"=>"tag2"
},
{
"value"=>"tag3"
}
]
Things quickly get out of control when adding to the bad response. Before submitting:
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错误,可以做些什么来解决它?