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

此生再无相见时 提交于 2019-11-27 03:54:15

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
Austin Nash

Routing Error

No route matches {:action=>"vote_up", :controller=>"microposts", :id=>nil}

this is the link I am using and assume this is where the routing isn't being specified correctly. I ran rake routes and there is a route called vote_up_micropost. Is there anything else I should look into. Thank you

here is the link I added

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

This is just a continuation of Brady's answer.

Brady had the following code in his view

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

what he means is.. since link_to by default uses :method => 'get' & he wanted to update the record using post & not get so he is using :method => 'post'

U can use <%= button_to('vote for this post!', vote_up_post_path(@post) %>, because button by default uses :method => :post

so the routes should be

resources :posts do
  member do
    post :vote_up
  end
end

here in post :vote_up inside the member, its the method => :post & not the post controller

but if you are determined to use link_to without :method => :post something like this

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

then your routing should be

resources :posts do
   member do
      get :vote_up
   end
end

Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!