我试图从查询数据库的结果中形成一个数组
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:#
的未定义方法`each'
我在这里做错了什么?
这是j['Categories']
的样子
Disability Support Worker: Disability Support Worker
答案 0 :(得分:3)
使用内置的pluck
方法:
Industry.where(name: j['Categories']).pluck(:name)
这比map
更高效:map
解决方案将检索每一列并为每条记录实例化一个Industry对象,然后在每个对象上调用name
方法。 pluck
将只检索给定的列并返回一个字符串数组。