我想在浏览器控制台或页面上打印一条消息,以便我可以确切地看到每个方法的调用时间。什么都没有打印,我没有找到一个有效的解决方案。我尝试使用flash消息,但它也没有用。我正在学习Rails,所以我想确切地看到被调用的内容以及何时调用。例如,如果调用了create,我想看到一条消息“Create was called!”。我试过这个:
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
答案 0 :(得分:2)
使用记录器和尾部log/development.log
logger.debug "Method was called"
debug
级别日志记录仅记录在开发环境中。如果要登录生产,请使用info
答案 1 :(得分:0)
在控制器操作中使用puts不会在浏览器的网页上打印它。如果您使用Webrick,它将打印在运行服务器的终端中。 如果要在网页上打印,则需要在与此操作相对应的视图中执行此操作:
在 show.html.erb 中写道:
显示方法已被调用!
您可以使用操作中的Rails.logger在日志文件中记录语句。
Rails.logger.info "SHOW METHOD WAS CALLED!"
这将写入development.log / production.log文件,具体取决于您的应用程序运行的环境。