问题
I'm trying to allow users to vote on threads without having to sign in/up in order to increase user engagement. How do I do this? At the moment my current though process is to tie votes with the visitor's IP address in order to prevent multiple votes, though another issue is that request.remote_ip is not getting me the correct IP (I'm on a school network). Any suggestions? Thanks very much!
Vote action in Threads Controller
def upvote
@thread = Thread.find(params[:id])
current_user.up_vote(@thread)
flash[:message] = 'Thanks for voting!'
respond_to do |format|
format.html { redirect_to :back }
format.js
end
Vote routes
resources :threads do
member do
post :upvote
post :unvote
end
回答1:
I wrote acts as votable.
The whole idea behind this gem was to allow anything to vote on anything (so there is not hard dependency on a user, like in the situation you are describing).
If you do not want to use IP addresses to store votes then maybe you can use a unique ID that you tie to each session. This would be open to vote fraud, but it would allow anyone to vote without having an account.
You could do something like
session[:voting_id] ||= create_unique_voting_id
voter = VotingSession.find_or_create_by_unique_voting_id(session[:voting_id])
voter.likes @thread
You would need to setup a VotingSession model that acts_as_voter and maintains a unique voting id, but that should be really easy w/ rails.
Hope this helps
回答2:
Finished Code
Ultimately I decided to tie it into the user's ip address.
First you have to create a Session model and db table, then you make the model acts_as_voter, and in your controller action you add the following lines.
session[:voting_id] = request.remote_ip
voter = Session.find_or_create_by_ip(session[:voting_id])
voter.likes @thread
回答3:
@kyle K : if you are using Devise as I was, you can follow the following link for getting the guest user created for the anonymous user actions.
https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user
good thing with above is that you can also take care of handing over the guest user resources back to the actual signed in or registered user if the guest user converts within the same session using the 'logging_in' method as described in the article :)
what I did is:
voter = current_or_guest_user
voter.likes @thread
来源:https://stackoverflow.com/questions/7987378/how-do-i-set-up-acts-as-votable-to-not-require-user-sign-in