我在Rails 7应用程序上使用@yairEO/tagify。我几乎可以用了。它将作为有效的JSON保存到数据库中。如果在返回表单进行编辑之后,使用带有3个标记(例如tag1、tag2、tag3 )的标签提交表单,那么标签化将这3个单独的标记组合成一个标签。
从数据库:
[
{
"value":"tag1"
},
{
"value":"tag2"
},
{
"value":"tag3"
}
]来自irb recipe.tags
[
{
"value"=>"tag1"
},
{
"value"=>"tag2"
},
{
"value"=>"tag3"
}
]在提交之前:

提交后:

当增加不良反应时,事情很快就失控了。在提交之前:

提交后:

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
enddef recipe_params
params[:recipe][:tags] = JSON.parse(params[:recipe][:tags])
params.require(:recipe).permit(
:title, :subtitle, :tags
)
endedit.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发布于 2022-09-01 15:03:56
问题是Rails返回了一个Hash,但是表单需要JSON。
为了解决这个问题,我将表单中的数据转换为json:
<%= form.label tags %>
<%= form.text_field(tags, value: recipe[tags].to_json) %>另外,为了把它弄干,我继续从recipes_controller.rb中删除了这些
@recipe.update(tags: JSON.parse(params[:recipe][:tags]))
和
params[:recipe][:tags] = JSON.parse(params[:recipe][:tags])
然后将其添加到菜谱模型中:
protected
def convert_to_json
self.tags = JSON.parse(tags) unless tags.empty?
end但是,在转换之前,我们需要确保它是有效的JSON,否则我们最终会陷入最初的混乱:
private
def valid_json?(value)
result = JSON.parse(value)
result.is_a?(Hash) || result.is_a?(Array)
rescue JSON::ParserError, TypeError
false
end然后convert_to_json变成... unless tags.empty? || !valid_json?(tags)
现在似乎工作正常了!如果有人对如何使这个变得更干净/更快/更好有任何建议,请告诉我们。谢谢
https://stackoverflow.com/questions/73431599
复制相似问题