RoR - Link_to 带有来自每个循环的嵌套散列

RoR - Link_to with nested hash from an each loop

嵌套哈希参数有问题。产品有很多特点。假设产品 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 %>

知道我在做什么吗?

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

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

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

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

我只是遗漏了 %5B 和 %5D 之间的特征名称 - 不确定为什么没有显示特征名称。

已修复。将创建哈希拉到模型中:

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

不确定为什么内联不起作用,但这修复了它。在最初的问题之外需要一些额外的上下文,我当时没有意识到。向大家表示歉意和感谢。

您需要使用 map 而不是 eachEach returns 它正在运行的原始数组本身。而 map returns 块中的元素。