我正在尝试创建一个从API检索数据的rake任务。但是,我需要的数据包含来自不同模型的数据。
这是我的错误:
[
{
"id": 3,
"name": "Precision Agriculture",
"topics_owners_ids": "#<User::ActiveRecord_Associations_CollectionProxy:0x000000095fa498>",
"keywords_list": null,
"keywords": [
],
"organizations_list": null,
"organizations": [
],
"social_groups_list": null,
"feeds_list": null,
"articles_list": null,
"people": null
}
这是我的佣金任务:
namespace :fieldfacts do
desc "Export Topics"
task :export_topics => :environment do
out = []
File.open("public/topics.json","w") do |f|
Topic.all.each do |topic|
api = TopicsService.new()
topic_api = api.get(topic.topic_api_id)
out << {
'id' => topic.id,
'name' => topic.name,
'topics_owners_ids' => topic.users.id,
'keywords_list' => topic_api.keywords_list,
'keywords' => topic_api.keywords,
'organizations_list' => topic_api.organizations_list,
'organizations' => topic_api.organizations,
'social_groups_list' => topic_api.social_groups_list,
'feeds_list' => topic_api.feeds_list,
'articles_list' => topic_api.articles_list,
'people' => topic_api.people
}
end
f.write(JSON.pretty_generate(out))
end
end
end
如您所见,topics_owners_ids未返回正确的数据。我不知道如何获取它。
答案 0 :(得分:1)
topic.users
将为您提供集合对象,您需要选择ID。尝试
topic.users.pluck(:id)