event.start-6ren">
gpt4 book ai didi

ruby-on-rails - 事件记录和文件 : How do i write Json file with my data?

转载 作者:行者123 更新时间:2023-11-29 11:23:07 25 4
gpt4 key购买 nike

如何将表事件中的数据写入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)/事件.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,
"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

关于ruby-on-rails - 事件记录和文件 : How do i write Json file with my data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15270522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com