【问题标题】:Active Record and file: How do i write Json file with my data?Active Record 和文件:如何用我的数据编写 Json 文件?
【发布时间】:2013-03-07 11:53:54
【问题描述】:

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

在模型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

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

public/event.json

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

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord


    【解决方案1】:

    问题是您在循环中为@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
    

    【讨论】:

    • @eventJson 可以是本地的 eventJson 甚至更好的 event_json
    【解决方案2】:

    在这种情况下,您可能希望使用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
    

    【讨论】:

      【解决方案3】:

      你可以用下面的方式来做:

        def write_json
          File.open('public/event.json', 'w') { |f| f.write(Event.all.to_json) }
        end
      
      

      如果要保存特定的字段,可以这样:

        def write_json
          File.open('public/event.json', 'w') do |f|
            f.write(Event.select(:id, :start, :end, :title, :body, :status).to_json)
          end
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-27
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-08
        • 2011-03-06
        • 2017-02-15
        相关资源
        最近更新 更多