2017-05-30 75 views
0

我试图形成从结果我从quering数据库ROR - 循环遍历活动记录结果,并形成一个阵列

industries = Industry.find_by_name(j['Categories']).industries 

的结果是我得到的是有一个数组如下

[#<Industry id: 3717, staffroom_type: "Industry", name: "Home Service", created_at: "2016-01-19 02:33:30", updated_at: "2016-01-19 05:25:53", parent_id: nil, user_cannot_join_shortlists: false, location: "SYDNEY, NSW, 2000", latitude: -33.8674769, longitude: 151.2069776, shortlist_introduction_email_subject: nil, shortlist_introduction_email_body: nil, external_job_url_enabled: false, deleted: false, deleted_at: nil, account_id: 3506, create_group_permission: false, create_role_permission: false, edit_group_permission: true, uuid: "70ef9351-f517-40a9-a300-8c1078da033a", staffroom_image_file_name: nil, staffroom_image_content_type: nil, staffroom_image_file_size: nil, staffroom_image_updated_at: nil, staffroom_image_repository: "production", cached_staffroom_image_id: nil, industry_type_id: nil, company_id: nil, billed_to: "employer", admin_user_id: nil, send_job_notifications: true, do_not_feature_jobs: false, company_type: nil, company_type_other: nil, company_restriction: nil, shortlist_count: nil>, 
#<Industry id: 1624, staffroom_type: "Industry", name: "Aged and Disability Care", created_at: "2015-04-13 02:07:53", updated_at: "2017-05-30 10:49:17", parent_id: nil, user_cannot_join_shortlists: false, location: "NOT PROVIDED (Assuming Sydney, 2000)", latitude: nil, longitude: nil, shortlist_introduction_email_subject: nil, shortlist_introduction_email_body: nil, external_job_url_enabled: false, deleted: false, deleted_at: nil, account_id: 3506, create_group_permission: false, create_role_permission: false, edit_group_permission: true, uuid: "f4b7bac3-3587-4056-a88f-9a9e98c42197", staffroom_image_file_name: nil, staffroom_image_content_type: nil, staffroom_image_file_size: nil, staffroom_image_updated_at: nil, staffroom_image_repository: "production", cached_staffroom_image_id: nil, industry_type_id: nil, company_id: nil, billed_to: "employer", admin_user_id: nil, send_job_notifications: true, do_not_feature_jobs: false, company_type: nil, company_type_other: nil, company_restriction: nil, shortlist_count: nil>] 

我想这个结果转换成一个数组,只是看起来像这样

['Home Service', 'Aged and Disability Care'] 

这些都是name我从数据库中获得的行业。

这就是我想

 industries.each do |industry| 
     ind[] = industry['name'] 

     end 

但是这给了我一个错误

NoMethodError: undefined method `each' for #<Industry:0x007fedba4addc8> 

我到底做错了什么?

这是j['Categories']看起来像

Disability Support Worker: Disability Support Worker 
+0

快速提问 - 如果您正在使用'find_by_name'或'where'(name:...)''从'['Categories']'并选择行业名称......您能不能只使用'j ['Categories']'的价值? (如果没有,@Jordan有正确的答案:) :) – SRack

回答

3

使用内置pluck方法:

Industry.where(name: j['Categories']).pluck(:name) 

这将是更高性能比map:本map解决方案将检索每一列和实例每个记录都有一个Industry对象,然后在每个对象上调用name方法。 pluck将只检索给定的列并返回一个字符串数组。

+2

亲爱的downvoter:请花点时间留下评论,解释你downvote的原因。如果我的答案缺乏,我会很高兴有机会改进它。 –

+0

非常感谢 – Saadia