【发布时间】:2017-06-21 21:09:12
【问题描述】:
我有一个哈希数组 - @profiles 的数据如下:
[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]
我想获取 user_id = 7 的全名?我正在执行以下操作:但它会抛出一个错误,即表达式 @profiles.find{|h| h[':user_id'] == current_user.id} 为 nil。
name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']
如果我使用 select 而不是 find 则错误是 - 没有将 String 隐式转换为 Integer。
如何搜索哈希数组?
更新:
在@Eric 的回答之后,我重新构建了我的工作模型和视图操作:
def full_names
profile_arr||= []
profile_arr = self.applications.pluck(:user_id)
@profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
@full_names = @profiles.each_with_object({}) do |profile, names|
names[profile[:user_id]] = profile[:full_name]
end
end
在视图中......,
p @current_job.full_names[current_user.id]
【问题讨论】:
标签: ruby-on-rails arrays ruby hash