2014-03-01 28 views
0

好吧,依靠導的博客教程:http://edgeguides.rubyonrails.org/getting_started.html如何找到一個評論個性化......甚至文章數

努力學習如何編寫一個方法我自己。

該指南做了文章和評論即,belongs_to & has_many關係。

所以,想到爲什麼不試着找出所有的評論。

這是我寫的評論控制器的方法:

def total_number_of_comments 
     @article = Article.all 
     @comments_total = @article.comments.count 
    end  

然後我把這個文章的觀點index.html.erb

<p>Total number of comments:</p> 

<%= @comments_total %> 

在索引頁,它不顯示任何東西。

那麼,我做錯了什麼?

而且,我不想要一個「正確的」答案。我想了解我在這裏錯過了什麼。

但我在這裏困惑的是如何思考這一點。

我毫不猶豫地這樣做,因爲它會延長帖子,但我想爲什麼不嘗試做文章計數。

所以,這裏是我所做的:

在文章模型

 def self.total_number_of_articles 
      Article.all.count 
     end 

在第二十控制器

def total_number_of_articles 
     @articles_total = Article.total_number_of_articles 
    end 

然後在文章查看index.html.erb再次,我把這個:

<p>Total number of articles:</p> 

<%= @total_number_of_articles %> 

再一次,在評論或文章中沒有任何數字顯示。

所以....很清楚,我在這裏錯過了一些東西。

編輯

註釋(total_number_of_comments)方法八九不離十在此基礎上:(從railsguide)

def create 
    @article = Article.find(params[:article_id]) 
    @comment = @article.comments.create(comment_params) 
    redirect_to article_path(@article) 
end 
+0

Rails控制器呈現與您正在調用的動作相對應的視圖(除非使用'render'或其他東西)。因此,如果您顯示的是index.html.erb,則不會調用控制器中的total_number_of_comments,除非您在過濾器之前執行此操作,可以使用'index'方法手動調用它,或者將相關代碼移動到'index'。 –

+0

@MichaelKohl,對不起,在回覆中寫了一條評論,然後刪除了它。你是什​​麼意思將代碼移動到索引?噢,你的意思是將該方法放在index.html.erb中?這是不是反對MVC的整個點?如何在過濾器之前執行此操作,或者從索引方法手動調用它? – user273072545345

+0

查看@ user2005659的答案誰正試圖向你解釋相同的問題。 –

回答

0

有很多事情你錯過了,我很樂意向你解釋。

  1. 這裏

    def total_number_of_comments 
    @article = Article.all 
    @comments_total = @article.comments.count 
    end 
    

    你必須要做到這一點

    def total_number_of_comments 
        @comments_total = Comment.all.count // simple solution 
    end 
    
  2. 下一個是,你沒有使用正確的實例變量。

    def total_number_of_articles 
        @articles_total = Article.total_number_of_articles 
    end 
    

    看到自己

    的文章總數:

    <%= @total_number_of_articles %> // this is wrong 
    

    您分配@articles_total但使用@total_number_of_articles。如果你使用@articles_total它會正常工作。

0

你應該在你的控制器定義函數索引。 調用GET/articles/index調用控制器功能索引,您應該在控制器的索引函數中設置@articles_total = Article.total_number_of_articles。你的控制器中沒有被調用的函數。