2017-05-30 76 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