2017-12-05 1 views
0

私は現在、 'acts_as_votable' Ruby gemを使用して、基本レールアプリのコメントにUpvote/Downvote関数を与えています。Rail appのビューでUpvote/Downvoteの数を表示できません

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で:comments_controller.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 %> 
以下のエラーを返して10

:私はこれが宝石に組み込まれている方法、またはルビーの方法のいずれかであると仮定した方法が定義されていない理由を

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

は私はわかりません。私はこれが何か他の理由のために投げられたエラーメッセージであるかどうかもわかりませんが、これが何であるか分かりません。代わりに 'upvote_from'を使用しようとしましたが、これはうまくいきませんでした。私が行を削除すると、アプリは正常に動作します。

他に何が起こっているのか分からないので、ここで感謝しています。

+0

なぜ '@ comment.each'を呼びますか?ビューの例はどこから取得しましたか?何を正確に表示しようとしていますか? –

+0

これは私がループを使用している理由のコメント/インデックスにあります。私はちょうど彼女の瞬間のコメントあたりの投票数にしようとしています。 – Robert

+0

それから '@ comment'ではなく' @ comments'でなければならないと思います。そしてあなたは 'upvote_by'を' w'で直接呼び出そうとしましたか? –

答えて

0

あなたは、インデックス内にある場合、私は@commentsの代わり@commentを使用するrecommandでしょう、それがコメントだより明らかだように、私はまたcommentためwの名前を変更します。

<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> 
+0

ありがとうございますが、残念ながら、それらの「集計」メソッドは同じ場所では動作しませんので、そうではないと思います。すべてのメソッドはまだ定義されていないとして表示され、それは私が本当に混乱している。 – Robert

0

マイグレーションを実行することを忘れないでください:

rails generate acts_as_votable:migration 
rake db:migrate 

あなたのコメントモデル(comment.rb)doc

Database Migrations

Acts As Votable uses a votes table to store all voting information. To generate and run the migration just use.

rails generate acts_as_votable:migration rake db:migrate

You will get a performance increase by adding in cached columns to your model's tables. You will have to do this manually through your own migrations. See the caching section of this document for more information.

Usage Votable Models

class Post < ActiveRecord::Base
acts_as_votable

end

acts_as_votable 

詳細にこれを追加

関連する問題