Rails - Soulmate,每行输出一件json

时间:2013-06-27 09:56:13

标签: ruby-on-rails json rake ruby-on-rails-4

我正在尝试使用Soulmate进行搜索和自动完成。但是它需要一个json文件,其中包含模型下的所有数据和每行一个项目。当我使用to_json导出时,我将所有对象用逗号分隔。

这就是我要打印的内容:

{"id":1,"term":"Dodger Stadium","score":85,"data":{"url":"\/dodger-stadium-tickets\/","subtitle":"Los Angeles, CA"}}
{"id":28,"term":"Angel Stadium","score":85,"data":{"url":"\/angel-stadium-tickets\/","subtitle":"Anaheim, CA"}}
{"id":30,"term":"Chase Field ","score":85,"data":{"url":"\/chase-field-tickets\/","subtitle":"Phoenix, AZ"}}
{"id":29,"term":"Sun Life Stadium","score":84,"data":{"url":"\/sun-life-stadium-tickets\/","subtitle":"Miami, FL"}}
{"id":2,"term":"Turner Field","score":83,"data":{"url":"\/turner-field-tickets\/","subtitle":"Atlanta, GA"}}

这就是我用to_json打印的内容

[{"id":1,"first_name":"Philip","last_name":"nalle","location":"nallemia","email":"hejsan@hej.com","active":false,"created_at":"2013-06-26T15:00:38.990Z","updated_at":"2013-06-26T15:00:38.990Z"},{"id":2,"first_name":"Philip","last_name":"nalle","location":"hejsan123","email":"hejsan@asd.com","active":false,"created_at":"2013-06-26T15:01:45.905Z","updated_at":"2013-06-26T15:01:45.905Z"},{"id":3,"first_name":"hejsan","last_name":"hejsan","location":"asd","email":"asd@asda.com","active":false,"created_at":"2013-06-26T15:08:20.354Z","updated_at":"2013-06-26T15:08:20.354Z"},{"id":4,"first_name":"well well","last_name":"hello","location":"asd123","email":"asd@asd.com","active":false,"created_at":"2013-06-26T15:10:27.121Z","updated_at":"2013-06-26T15:12:29.991Z"}]

不介意json里面的实际数据,我只是从soulmates自述文件中复制了一个样本。这是佣金任务。

desc "Save all participants to json"
task :save_to_json => :environment do
    File.open("participants.json", "w") { |f| f.write(Participant.all.to_json)} 
end

1 个答案:

答案 0 :(得分:1)

要实现您的目标,您需要逐个输出元素。 它还可以节省内存,如果不是.all,如果它们中有很多,你会抓住它们。

desc "Save all participants to json"
task :save_to_json => :environment do
    File.open("participants.json", "w") do |f| 
        Participant.all.each do |participant| 
            f.write("#{participant.to_json}\n")
        end
    end
end