db14
db14

Reputation: 117

How to create new object using data from icalendar file

I have a model called event which attributes are:

     string "name"
     string "location"
     string "lecturer"
     date "start_time"
     date "end_time"`

I want to take data from icalendar type file and create event instances. How should I do this ? I tried to do a method in 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

But then what I should do with it ? Should I call this function in view or maybe should I take this code to method called create which looks like this:

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

Upvotes: 0

Views: 56

Answers (1)

widjajayd
widjajayd

Reputation: 6263

my understanding calendar2.ics have many records, if you want to loop through all the event inside calendar2.ics and save it to your event table (import ics file to event table)

below are sample steps, inside your routes file create one method

resources :events do
  collection {
    get  :transfer_data_from_ics
  }
end

inside your events_controller you create 2 methods

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

to get the method called you can create menu / button with link_to as follow:

<%= link_to "Transfer data", transfer_data_from_ics_events_path %>

Upvotes: 1

Related Questions