Rails:从表单向服务器发送哈希数组

时间:2014-08-19 17:11:05

标签: ruby-on-rails

在我的参数哈希中,我试图实现以下内容:

{"utf8"=>"✓", "authenticity_token"=>"6A14fVUEWQSB83j2BsYKn", "search"=>{"keywords"=>[{"keyword_names"=>"color", "keyword_conditions"=>"is not", "keyword_values"=>"red"}, {"keyword_names"=>"size", "keyword_conditions"=>"is", "keyword_values"=>"3"}] , "assignee_id"=>"", "begin_date"=>"", "end_date"=>""}, "commit"=>"search"}

请注意以下事项:

"keywords"=>[{"keyword_names"=>"color", "keyword_conditions"=>"is not", "keyword_values"=>"red"}, {"keyword_names"=>"size", "keyword_conditions"=>"is", "keyword_values"=>"3"}]

然而,这是目前正在发送的内容:

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6A14fVUEWQSB83j2BsYKn", "keyword_names"=>["name", "name"], "keyword_conditions"=>["is", "is"], "keyword_values"=>["dan", "john"], "search_add"=>"and", "search"=>{"assignee_id"=>"", "begin_date"=>"", "end_date"=>""}, "commit"=>"search"}

注意keyword_names,keyword_conditions和keyword_values不是搜索哈希的一部分。如何将其作为搜索哈希的一部分?

这就是我所拥有的:

  <%= link_to "Add", "#", class: 'add_search'  %>
  <div class="search_container">
    <%= text_field_tag "keyword_names[]" %><%= select_tag "keyword_conditions[]", options_for_select(["is", "is not","is like"]) %><%= text_field_tag "keyword_values[]" %>
  </div>

1 个答案:

答案 0 :(得分:1)

遵循params的这种结构:

keywords: 
  [
    { keyword_names: 'color', keyword_conditions: 'is not', keyword_values: 'red' }
  ]

您应该将输入命名为:

0..3.each do |index|
  text_field_tag "keywords[#{index}][keyword_names]"
  select_tag "keywords[#{index}][keyword_conditions]", options_for_select(['is', 'is not', 'is like'])
  text_field_tag "keywords[#{index}][keyword_values]"
end

0..3.each do |index|是一个循环,为每个关键字定义4个不同的3个输入集。因此params[:keywords].size应该返回4