如何将所有选中的复选框值作为数组发布到1个字段?

时间:2014-09-17 18:32:10

标签: ruby-on-rails ruby postgresql ruby-on-rails-4

将数据发布并保存到postgres db。

<% ['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

1 个答案:

答案 0 :(得分:1)

你几乎得到了它:

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

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

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