【问题标题】:RoR - Link_to with nested hash from an each loopRoR - 来自每个循环的嵌套散列的 Link_to
【发布时间】:2016-04-08 17:26:33
【问题描述】:

嵌套散列参数有一些问题。产品有很多特点。假设产品 1 具有功能 foo 和 baz。

我想同时传递产品和所有功能来查询 link_to 中的字符串参数,以便它最终看起来像这样:

"/puppies/new?features%5Bbaz%5D=qux&features%5Bfoo%5D=bar&product=1"

我目前正在尝试这个,它会出现语法错误,原因可能对我以外的人来说是显而易见的。

<% Product.each do | product | %>
  <%= link_to(new_puppy_path(product: product, features: { product.features.each 
    { | feature| feature.name : 'feature.'} } ), class: 'slorp') do %>
    // stuff inside the link
  <% end %>
<% end %>

知道我在这里做了什么蠢事吗?

更新:我已将代码更新为:

&lt;%= link_to(new_puppy_path(product: product, features: product.features.each{|feature| {feature.name.to_sym =&gt;feature.feature_colors.first}}), class: 'image') do %&gt;

这更接近了,因为我的输出 URL 现在是:

/puppies/new?features%5B%5D=3&features%5B%5D=2&product=2

我只是缺少 %5B 和 %5D 之间的功能名称 - 不知道为什么功能名称没有显示。

【问题讨论】:

  • 请贴出错误信息
  • feature.name : '功能。' - 我不明白这是应该输出的代码吗?
  • 目标是将参数输出为代码 sn-p - %5Bbaz%5D=qux 上方的 URL 中的参数。更新了一些我尝试过的新东西,效果更好,但仍然缺少一些东西。

标签: ruby-on-rails ruby ruby-on-rails-4 hash params


【解决方案1】:

您需要使用 ma​​p 而不是 each每个返回它正在操作的原始数组本身。而 ma​​p 从块中返回元素。

【讨论】:

  • 太棒了。这也奏效了,这也是我今后将使用的。非常感谢您的解释。
【解决方案2】:

已修复。将创建散列拉到模型中:

def reco_features
  list = Hash.new
  feature_colors.each do |feature_color|
      list[feature_color.feature.name] = feature_color.id
  end
  return list
end

然后更新了link_to:

<%= link_to(new_puppies_path(product: product, features: features.reco_features ), class: 'slorp') do %>

不知道为什么内联不起作用,但这修复了它。在最初的问题之外需要一些额外的背景,我当时没有意识到。向大家道歉并感谢大家。

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2022-01-05
    • 2013-08-07
    相关资源
    最近更新 更多