簡體   English   中英

無法在Rail應用程序視圖中顯示Upvote / Downvote計數

[英]Unable to display Upvote/Downvote count in Rail app views

我當前正在使用'acts_as_votable'Ruby gem將Upvote / Downvote函數提供給基本Rails應用程序中的注釋。 在comments_controller.rb中,函數如下所示:

    def upvote
      @comment = Comment.find(params[:id])
      @comment.upvote_by current_user
      redirect_to comments_path
    end

    def downvote
      @comment = Comment.find(params[:id])
      @comment.downvote_by current_user
      redirect_to comment_path
    end

並在roputes.rb中:

  resources :comments do
    member do
     put "like", to: "comments#upvote"
     put "dislike", to: "comments#downvote"
    end
  end 

並且視圖中的循環如下所示:

 <div class="box">
 <% @comment.each do |w| %>
    <tr>        
      <td><b><%= w.title %></b></td><br>
      <td><%= w.location %></td><br>
      <td><%= w.body %></td><br> 
      <%= link_to "upvote", like_comment_path(w), method: :put %>
      <%= @comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(w), method: :put %>
      </tr>
    <% end %>
 </div> 

除了下面這行代碼,這沒有問題:

<%= @comment.upvote_by.size %>

返回以下錯誤:

undefined method `upvote_by' for #
<Comment::ActiveRecord_Relation:0x007faa8dbf0560>

我不確定為什么未定義該方法,因為我假設這是內置在gem中的方法或ruby方法。 我也不知道這是否是由於其他原因引發的錯誤消息,但是我不確定這可能是什么。 我嘗試使用“ upvote_from”代替,但這沒有用。 如果我刪除該行,則該應用程序運行正常。

我無法弄清楚是什么原因引起的,所以在此我非常感謝您的幫助。

如果您在索引中,我將建議使用@comments而不是@comment ,我還將重命名wcomment以便更清楚地表明它是注釋。

<div class="box">
 <% @comments.each do |comment| %>
    <tr>        
      <td><b><%= comment.title %></b></td><br>
      <td><%= comment.location %></td><br>
      <td><%= comment.body %></td><br> 
      <%= link_to "upvote", like_comment_path(comment), method: :put %>
      <%= comment.upvote_by.size %>
      <%= link_to "downvote", dislike_comment_path(comment), method: :put %>
      </tr>
    <% end %>
 </div> 

不要忘記運行遷移:

rails generate acts_as_votable:migration
rake db:migrate

將此添加到您的評論模型中(comment.rb)

acts_as_votable

文檔中的更多詳細信息

數據庫遷移

作為投票者行動使用投票表存儲所有投票信息。 要生成並運行遷移,只需使用。

rails產生acts_as_votable:migration rake db:migrate

通過將緩存的列添加到模型的表中,可以提高性能。 您將必須通過自己的遷移手動執行此操作。 有關更多信息,請參見本文檔的緩存部分。

用法可變模型

類Post <ActiveRecord :: Base
actions_as_votable

結束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM