Freitag, 20. Juni 2008

From file to DB through Controller

This method reads data from an uploaded file in a , delimited file and stores it in the database in the movies, categories and category_movies(join table).

category name 1, category name 2, ...., category name x: movie title

def create

while (line=params[:dvd_data].gets)
title=line.scan(/ROOT:.*/).to_s.gsub(/ROOT:/,"")
categories=line.gsub(/ROOT:.*/,"").scan(/.+?,/)
categories.each do |category|
category.gsub!(/,/,"")
the_category = Category.find_or_create_by_name(:name => category)
the_movie= Movie.find_or_create_by_title(:title => title.to_s)
CategoryMovie.find_or_create_by_category_id_and_movie_id(:category_id =>the_category.id, :movie_id=> the_movie.id)
end
end


respond_to do |format|
flash[:notice] = 'DataBase Updated With DVD titles and Categories'
format.html { redirect_to(category_movies_path) }
format.xml { render :xml => @category_movie, :status => :created, :location => @category_movie }
end
end

Keine Kommentare: