Clarification on how to use “thumbs_up” voting gem with Rails 3

后端 未结 3 778
悲&欢浪女
悲&欢浪女 2020-11-30 03:27

I am attempting to implement the thumbs_up voting gem on a Rails 3 app, however the instructions are unclear on the actual implementation. After requiring the gem [g

3条回答
  •  無奈伤痛
    2020-11-30 03:57

    Hopefully I can help you out a bit.

    The generators should have created a Vote model for you. This is the model that holds all the votes, but that you interact with indirectly through the methods you've described above.

    So, for you:

    class User < ActiveRecord::Base
      acts_as_voter
    end
    
    class Post < ActiveRecord::Base
      acts_as_voteable
    end
    

    That will get you set up with the thumbs_up methods in each of the models.

    Then for example, if you have a controller action in PostsController that is linked to from an "up arrow" on your website, you can create a vote for that user for that post.

    A view like this:

    <%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>
    

    and a routes.rb like this:

    resources :posts do
      member do
        post :vote_up
      end
    end
    

    And finally, in the controller:

    class PostsController < ApplicationController
      def vote_up
        begin
          current_user.vote_for(@post = Post.find(params[:id]))
          render :nothing => true, :status => 200
        rescue ActiveRecord::RecordInvalid
          render :nothing => true, :status => 404
        end
      end
    end
    

提交回复
热议问题