saving data from database to text/yaml file

138 views
Skip to first unread message

Gautam

unread,
Mar 29, 2010, 9:22:20 PM3/29/10
to Ruby on Rails: Talk
Hello all...

I am new to rails.
I have a rails app in which i want data from my database table into a
text file.

I have a notices table that has three fields - title, body and user. I
want this data to be stored in a text or yaml file.

Here is the code of what I am trying to do... But I am not able to get
it done.

def save
@notice = Notice.find(params[:id])
f = File.new("#{RAILS_ROOT}/public/notice.txt","w")
debugger
f.write @notice
f.close
end


Please help me.

Me

unread,
Mar 30, 2010, 12:04:14 PM3/30/10
to Ruby on Rails: Talk
@notice is an object. you need to write each attribute to the file.

f.write @notice.title
f.write @notice.body
f.write @notice.user

Gautam

unread,
Mar 30, 2010, 6:17:40 PM3/30/10
to Ruby on Rails: Talk
Thank you for your reply...
I am posting code for my controller - notices.
The save method is at the last. I am not able to link and call this
method and its not working as well.
Please correct the code and help me.

class NoticesController < ApplicationController


def index
@notices = Notice.all

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @notices }
end
end


def show


@notice = Notice.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @notice }
end
end


def new
@notice = Notice.new

respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @notice }
end
end


def edit


@notice = Notice.find(params[:id])

end


def create
@notice = Notice.new(params[:notice])

respond_to do |format|
if @notice.save
flash[:notice] = 'Notice was successfully created.'
format.html { redirect_to(@notice) }
format.xml { render :xml => @notice, :status
=> :created, :location => @notice }
else
format.html { render :action => "new" }
format.xml { render :xml => @notice.errors, :status
=> :unprocessable_entity }
end
end
end


def update


@notice = Notice.find(params[:id])

respond_to do |format|
if @notice.update_attributes(params[:notice])
flash[:notice] = 'Notice was successfully updated.'
format.html { redirect_to(@notice) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @notice.errors, :status
=> :unprocessable_entity }
end
end
end


def destroy


@notice = Notice.find(params[:id])

@notice.destroy

respond_to do |format|
format.html { redirect_to(notices_url) }
format.xml { head :ok }
end
end

def save
@notice = Notice.find(params[:id])

f = File.new("#{RAILS_ROOT}/public/jar/notice.txt","w")
f.write @notice.title
f.write @notice.body
f.write @notice.user_name
f.close
end

end

Reply all
Reply to author
Forward
0 new messages