Reputation: 999
I want to print a message to the browser console or to the page so I can see exactly when each method is called. Nothing is being printed and I haven't found a working solution. I tried using flash messages but it didn't work as well. I'm learning Rails so I want to see exactly what is being called and when. For example if create was called I want to see a message "Create was called!". I have tried this:
class PostsController < ApplicationController
# only index, show, new, and edit pages will have views
# create, update, and destroy will do some kind of work and then redirect
# instance variables are visible in our view files
def index
@posts = Post.all
end
def show
# find the post and find the id that was passed into the url
@post = Post.find(params[:id])
flash[:success] = "SHOW WAS CALLED IN FLASH"
puts "SHOW METHOD WAS CALLED!"
end
def new
@post = Post.new
end
def create
@post = Post.new(params[:post])
if @post.save
redirect_to(posts_path, :notice => "Your post was saved!")
else
render "new"
end
end
def edit
puts "<p>EDIT METHOD WAS CALLED!</p>"
@post = Post.find(params[:id])
end
def update
puts "UPDATE METHOD WAS CALLED!"
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
redirect_to posts_path, :notice => "Your post has been saved."
else
render "edit"
end
end
def destroy
puts "DESTROY METHOD WAS CALLED!"
@post = Post.find(params[:id])
@post.destroy
redirect_to(posts_path, :notice => "Post deleted")
end
end
Upvotes: 0
Views: 345
Reputation: 29349
Use logger for this and tail log/development.log
logger.debug "Method was called"
debug
level logging will only be logged in development environment. use info
if you want to log in production
Upvotes: 2
Reputation: 4980
Using puts in the controller action won't print it on the web page in the browser. It will be printed in the terminal where your server is running in case you are using Webrick. If you want to print it on the webpage, you need to do so in the view corresponding to the action like this:
In show.html.erb write:
SHOW METHOD WAS CALLED!
You can log the statements in the log files using Rails.logger in the action.
Rails.logger.info "SHOW METHOD WAS CALLED!"
This will be written to the development.log/production.log file depending on which environment your application is running.
Upvotes: 0