如何将表事件中的数据写入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.json文件?
公共/ event.json
{"id":35,"start":"2013-03-28T00:00:00Z","end":"2013-03-28T00:00:00Z","title":"1345edrewrewr","body":"123124","status":"Confirm"}
解决方法
问题是您在循环中为@eventJson赋值,以便先前的值丢失.你应该使用一个数组:
def write_json events_json = [] Event.all.each do |event| event_json = { "id" => event.id,"status" => event.status } events_json << event_json end File.open("public/event.json","w") do |f| f.write(events_json.to_json) end end