0

検索とオートコンプリートを行うために Soulmate を使用しようとしています。ただし、モデルの下にあるすべてのデータと 1 行に 1 つの項目を含む 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 の readme からコピーしただけです。これがレーキタスクです。

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
4

1 に答える 1

1

目的を達成するには、要素を 1 つずつ出力する必要があります。また、.all の代わりに 1000 単位で取得すると、メモリが節約されます。

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
于 2013-06-27T10:04:37.093 に答える