postgresql Active Record 和文件:如何用我的数据编写 Json 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15270522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:49:30  来源:igfitidea点击:

Active Record and file: How do i write Json file with my data?

ruby-on-railspostgresqlactiverecord

提问by King Dark

How do I write a data in table event to json file? Please see this code:

如何将表事件中的数据写入 json 文件?请看这个代码:

In model event.rb

在模型 event.rb

 class Event < ActiveRecord::Base
  attr_accessible :name, :event_description, :start_at, :end_at, :status, :eventable_id
  has_event_calendar
  belongs_to :eventable, polymorphic: true
  after_save :write_json


end
def write_json
    Event.all.each do |event|
            @eventJson = {
            "id" => event.id,
            "start" => event.start_at,
            "end" => event.end_at,
            "title" => event.name,
            "body" => event.event_description,
            "status" => event.status
            } 

    end
    File.open("public/event.json","w") do |f|
      f.write(@eventJson.to_json)
    end 

 end

In file Jsonthere's one record, but in table eventthere are many records. How do I write all records from table eventto event.json file after saving the record?

在文件中Json有一条记录,但在表中event有许多记录。event保存记录后,如何将表中的所有记录写入event.json 文件?

public/event.json

公共/事件.json

{"id":35,"start":"2013-03-28T00:00:00Z","end":"2013-03-28T00:00:00Z","title":"1345edrewrewr","body":"123124","status":"Confirm"}

回答by Ilya Khokhryakov

The problem is that you assign a value to @eventJsonin a loop so the previous values are lost. You should use an array:

问题是您@eventJson在循环中分配了一个值,因此之前的值会丢失。你应该使用一个数组:

def write_json
  events_json = []
  Event.all.each do |event|
    event_json = {
      "id" => event.id,
      "start" => event.start_at,
      "end" => event.end_at,
      "title" => event.name,
      "body" => event.event_description,
      "status" => event.status
    } 
    events_json << event_json
  end
  File.open("public/event.json","w") do |f|
    f.write(events_json.to_json)
  end 
end

回答by PBJ

In this case, you might want to use mapinstead of each-- it's much cleaner. Given that you said the method is in the model, this is how it would look.

在这种情况下,您可能想要使用map而不是each- 它更干净。鉴于您说该方法在模型中,这就是它的外观。

class Event < ActiveRecord::Base
    ...

    def self.write_json
      record_json = self.all.map{ |record| { self.name => record.attributes } }.to_json
      File.open("#{Rails.root}/#{(self.name.underscore)}.json", "w") do |f|
        f.write record_json
      end 
    end
end