我有一个称为事件的模型,其属性为:
string "name"
string "location"
string "lecturer"
date "start_time"
date "end_time"`
我想从icalendar类型文件中获取数据并创建事件实例。我该怎么办?我试图在events_controller.rb
中做一个方法:
def new_method
@ievent_file = File.open("calendar2.ics")
@ievents = Icalendar::Event.parse(@ievent_file)
@ievent = @ievents.first
@ievent = Event.new(name:@ievent.summary,location:@ievent.location, lecturer:@ievent.description, start_time:@ievent.dtstart, end_time:@ievent.dtend)
end
但是我应该怎么做呢?我应该在视图中调用此函数,还是应该将此代码带到名为create
的方法中,该方法如下所示:
def create
@event = Event.new(event_params)
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render :show, status: :created, location: @event }
else
format.html { render :new }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:1)
如果您想遍历calendar2.ics内的所有事件并将其保存到事件表(将ics文件导入事件表)中,我的理解calendar2.ics有很多记录
下面是示例步骤,在您的路线文件中创建一种方法
world['iso_a2'] = world['iso_a3'].replace(countries.set_index('alpha-3')['alpha-2'])
在events_controller内部,您创建2个方法
resources :events do
collection {
get :transfer_data_from_ics
}
end
要获取调用的方法,您可以使用link_to创建菜单/按钮,如下所示:
def transfer_data_from_ics
# get data from ics
@ievent_file = File.open("calendar2.ics")
@ievents = Icalendar::Event.parse(@ievent_file)
# loop through
@ievents.each do |i_event|
Event.create(
name: i_event.summary,
location: i_event.location,
lecturer: i_event.description,
start_time: i_event.dtstart,
end_time: i_event.dtend)
end
# route back to events list
redirect_to events_path
end