首页 > 解决方案 > 如何从rails中的数组中获取artistID并使用artistID作为参数进行重定向

问题描述

我是 Rails 新手,正在制作一个测试应用程序,但在从数组中获取键/值时遇到了一些麻烦。

我想按艺术家姓名搜索艺术家。找到匹配项后,我想转到基于艺术家 ID 的个人简介页面。按名称搜索按预期工作,但我无法使用艺术家 ID 进行重定向。这是我的艺术家 ID 代码。

@artists = ["artists": {"artistName": "Nirvana", "artistID": "0001", "album": "Nevermind"}, {"artistName": "Pearl Jam", "artistID": "0201", "album": "Ten"}, {"artistName": "Alice In Chains", "artistID": "1192", "format": "Sap"}}]

@artists.each do |item|
 @artistID = item[:artistID]
end

@artistID 的结果始终是数组中的最后一个艺术家 ID。我也试过这个

@artistID = Array.new
@artists.each do |item|
 @id = Hash.new
 @id = item[:artistID]
@artistID << @id
end

然后返回所有的艺术家 ID。谁能帮我获得艺术家的正确艺术家 ID?

标签: ruby-on-railsarraysruby

解决方案


第一行不是有效的数组,您也没有进行任何比较来查找 ID。在第一个中,您将@artistID变量分配给每个艺术家 ID,最后只剩下最后一个。另一个示例是将所有 ID 复制到一个数组中。看看这个:

artists = [
  {"artistName": "Nirvana", "artistID": "0001", "album": "Nevermind"},
  {"artistName": "Pearl Jam", "artistID": "0201", "album": "Ten"},
  {"artistName": "Alice In Chains", "artistID": "1192", "format": "Sap"}
]

found_artist = artists.find do |artist|
  artist[:artistName] == "Nirvana"
end

artistID = found_artist[:artistID]
puts artistID

这将为我打印“0001”。


推荐阅读