rewrite source code

improve source code for easy reading.
change from sql query to active record
and shorten long insert/update active record.