2014-04-10 23 views
0

我想打印一條消息到瀏覽器控制檯或頁面,以便我可以準確瞭解何時調用每個方法。沒有任何內容正在打印,我還沒有找到工作解決方案。我嘗試使用Flash消息,但它沒有工作。我正在學習Rails,所以我想看看究竟是什麼以及什麼時候被調用。例如,如果創建被調用,我想看到一條消息「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

在控制器中使用puts操作不會將它打印在瀏覽器的網頁上。如果您使用的是Webrick,它將被打印在運行服務器的終端中。 如果你想打印的網頁上,你需要在視圖這樣做相應的像這樣的動作:

show.html.erb寫:

SHOW方法被調用!

您可以使用Rails.logger在操作中記錄日誌文件中的語句。

Rails.logger.info "SHOW METHOD WAS CALLED!" 

這將寫入到development.log/production.log文件,具體取決於您的應用程序運行的環境。

2

用於該用途的記錄和尾部log/development.log

logger.debug "Method was called" 

debug級別的日誌記錄將只在開發環境中進行記錄。如果您想登錄生產,請使用info