gpt4 book ai didi

ruby-on-rails - 如何将所有选中的 check_box 值作为数组发布到 1 个字段?

转载 作者:行者123 更新时间:2023-11-29 13:30:07 25 4
gpt4 key购买 nike

以数组形式发布并保存到 postgres 数据库。

<% ['auto', 'homeowners', 'health'].map do |service| %>
<div class="element element-float">
<%= check_box_tag 'agent[agent_services]', [service] %> <%= service %>
</div>
<% end %>

目前提交表单只会保存选中页面上的最后一项。因此,如果我尝试检查“汽车”和“房主”,则只会保存“房主”。 rails 日志:

"agent"=>{"agent_services"=>"homeowners"}

我需要做的是将所有选中的元素作为数组保存到 ROW#agent_services 中。因此,如果我选中“汽车”和“房主”,我需要发生以下情况:

"agent"=>{"agent_services"=>["auto", "homeowners"]}

我可以用 js 做到这一点,但我想知道 rails 的方式。另外下一个问题是 postgresql#agent_services == String ..有没有办法让这一行接受一个数组?

谢谢!

保存到 postgres 时出现问题列是 add_column :agents, :agent_services, :string, array: true

params.require(:agent).permit( . . . , :agent_services => [])

Processing by AgentsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t/aqjJWwd24czZNXKVS5q9yjf6WU15/artpAaXtb28s=", "agent"=>{"agent_services"=>["auto", "homeowners", "health"]}, "button"=>"", "id"=>"60"}
Agent Load (0.3ms) SELECT "agents".* FROM "agents" WHERE "agents"."id" = $1 LIMIT 1 [["id", 60]]
(0.1ms) BEGIN
SQL (0.5ms) UPDATE "agents" SET "agent_services" = $1, "updated_at" = $2 WHERE "agents"."id" = 60 [["agent_services", "{\"auto\",\"homeowners\",\"health\"}"], ["updated_at", "2014-09-17 18:50:52.190149"]]
PG::DatatypeMismatch: ERROR: column "agent_services" is of type character varying[] but expression is of type character varying at character 40
HINT: You will need to rewrite or cast the expression.
: UPDATE "agents" SET "agent_services" = $1, "updated_at" = $2 WHERE "agents"."id" = 60
(0.1ms) ROLLBACK

最佳答案

你几乎明白了:

check_box_tag 'agent[agent_services][]', [service]

将为您提供您想要的参数:

"agent"=>{"agent_services"=>["auto", "homeowners"]}

关于ruby-on-rails - 如何将所有选中的 check_box 值作为数组发布到 1 个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25897872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com