代码之家  ›  专栏  ›  技术社区  ›  alex

从参数合并哈希时出现问题-“未定义的方法到\u哈希”

  •  0
  • alex  · 技术社区  · 6 年前

    我正在尝试构建一个显示类别列表的页面。当你点击其中一个时,你会被带到同一个页面,但现在你会看到一个新的查询字符串,它是你刚刚选择的类别。然后可以选择另一个类别,允许它们堆叠。URL最终可能是这样的。

    http://localhost:3000/filter?categories%5B%5D=restaurant&categories%5B%5D=takeout
    

    在Rails视图中,我使用 link_to 来构建这些URL。当查询字符串中没有现有类别时,我只需在questions permalink中传递类别符号和类别的单个数组。当存在现有类别时,我想将新类别插入 request.query_parameters 类别数组,然后将其与请求合并。query\u参数作为一个整体。这样我将来也可以有子类别和订单/排序查询。

    <% @categories.each do |category| %>
    
        <% if !params.has_key?(:categories) %>
            <%= link_to category.category_name, shops_path(categories: [category.permalink]) %>
        <% else %>
            <%= link_to category.category_name, shops_path(request.query_parameters.merge(request.query_parameters[:categories] << category.permalink)) %>
        <% end %>
    
    <% end %>
    

    然后,我将使用永久链接搜索数据库中具有匹配永久链接的类别,并显示与URL中查询字符串中至少一个类别匹配的结果。

    单击第一个链接为请求创建如下哈希。从以下URL查询\u参数。

    {"categories"=>["restaurant"]}
    http://localhost:3000/filter?categories%5B%5D=restaurant
    

    第二个我想从下面的URL创建这样的哈希。

    {"categories"=>["restaurant","takeout"]}
    http://localhost:3000/filter?categories%5B%5D=restaurant&categories%5B%5D=takeout
    

    但是,我收到以下错误消息。

    undefined method `to_hash' for ["restaurant", "takeout"]:Array
    Did you mean?  to_h
    
    Request
    Parameters:
    
    {"categories"=>["restaurant", "takeout"]}
    

    我怎样才能避免这个错误?

    编辑

    找到了解决方案,因此将其作为答案发布。

    2 回复  |  直到 6 年前
        1
  •  0
  •   Rohan    6 年前

    看到您编写的日志和代码,您正在尝试将哈希合并到categories数组,这不是正确的方法。

    修改代码如下:

    <%= link_to category.category_name, shops_path(request.query_parameters[:categories] << category.permalink) %>
    

    上行将在categories数组中推送新类别,当在controller中接收到查询参数时,其他类别将合并到请求参数中。

        2
  •  0
  •   alex    6 年前

    我找到了解决办法。只需合并键为的数组 categories: 如果您在 request.query_parameters 搞砸如果您已经拥有该密钥,那么只需附加新的 category.permalink 具有 +=

    因此,解决方案扩展到了三个条件。

    1. 完全没有参数
    2. 参数,但没有键为 类别:
    3. 参数,键为 类别:

    希望这将有助于其他人在未来!

    <% if request.query_parameters.empty? %>
        <%= link_to category.category_name, shops_path(categories: [category]) %>
    <% else %>
        <% if !params.has_key?(:categories) %>
            <%= link_to category.category_name, shops_path( request.query_parameters.merge!(categories: [category])) %>
        <% else %>
            <%= link_to category.category_name, shops_path(request.query_parameters[:categories] += [category.permalink]) %>
        <% end %>
    <% end %>