ruby-on-rails - 如何从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?
解决方案
第一行不是有效的数组,您也没有进行任何比较来查找 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”。
推荐阅读
- mysql - 修复自动增量键 mysql 数据库的顺序
- spring-boot - Spring Security 5 OAuth2 WebClient [client_authorization_required] 客户端注册 ID 所需的授权:假人”
- node.js - 节点承诺链是否无法同步执行?
- php - 如何在limesurvey中上传文件
- python - 机器人框架 - UnicodeDecodeError:“ascii”编解码器无法解码位置 49 的字节 0xe9:输入文本时序数不在范围内(128)
- html - 为什么我的元素的内容区域超出其父元素?
- c++ - 可以乘一个旋转矩阵来旋转方向向量(vec 3)吗?
- lua - 有没有更快的方法在 lua 中找到素数?
- javascript - 优化在对象中查找嵌套属性的功能?
- r - 在 R 中创建新对象