xml generation using rails

hi all...
Here is how to do this:

create rails app

>> rails xml_generation -d mysql

create the database which u want to use and edit the name in database.yml
now create the model for 'xml_generation'

xml_generation>>ruby script/generate model student

edit the migration file created,

class CreateStudents < ActiveRecord::Migration
  def self.up
    create_table :students do |t|
      t.string :first_name
      t.string :last_name
      t.integer :age
      t.string :school_name
      :first_name => 'Monica',
      :last_name => 'Geller',
      :age  => 20,
      :school_name => 'Bhavans'
  def self.down
    drop_table :students

so now we need to generate the controller,

xml_generation>>ruby script/generate controller student

after that edit the controller with these codes,

class StudentController < ApplicationController
  def create_file
    @students = Student.find(:all)
    file = File.new('dir.xml','w')
    doc = REXML::Document.new
    make = REXML::Element.new "make"
    @students.each do |s|
      first_name_node = make.add_element "FirstName"
      first_name_node.text  = s.first_name
      last_name_node = make.add_element "LastName"
      last_name_node.text  = s.last_name
      age_node = make.add_element "Age"
      age_node.text  = s.age
      school_node = make.add_element "School"
      school_node.text  = s.school_name
    doc.add_element make
    file.puts doc

migrate the project

xml_generation>> rake db:migrate

time to run it

xml_generation>>ruby script/server

open a browser and goto to http://localhost:3000/student/create_file



Post a Comment