Coder Social home page Coder Social logo

thumbs_up's People

Contributors

arjun810 avatar boska avatar bouchard avatar dfischer avatar flyinventions avatar gregmolnar avatar guyisra avatar hugoabonizio avatar jerefrer avatar kossnocorp avatar ldewald avatar maddox avatar mixr avatar morgoth avatar nagybence avatar nickcoyne avatar oponder avatar pboling avatar peteonrails avatar spoonman avatar tonkpils avatar willayd avatar xlash avatar zeantsoi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

thumbs_up's Issues

Mongoid Support?

I'm not sure if you have any plans for making the gem usable with mongoid, but I'd Love to know if you do. I'm trying to monkeypatch a fix right now. I'll let you know if I make any progress.

Cannot use count/any?/empty? anymore

I was working on the new version of my app and realized when I was using things like

Article.tally.any?

or

Article.plusminus.empty? 

I had an error saying :

Mysql2::Error: Unknown column 'vote_count' in 'order clause'

or unkown 'plusminus_tally' for the latter.

Things were working just fine with 4.6. By briefly looking at this repo history I would say it appeared when you refactored the tally/plusminus methods, near 5.0.

Added failing tests cases. See : https://github.com/brady8/thumbs_up/pull/41

Feature Request: Wilson Score method

I've noticed that sorting on votable records with 'plusminus' often leaves me with strange results, depending on the number of votes one record may have in relation to another. Posts with a lower percentage of positive votes could be rated higher due to fact they have been around longer and have a larger pool of votes. I saw an article that clearly describes this problem and offers up a solution to it.

http://evanmiller.org/how-not-to-sort-by-average-rating.html

He bases the answer on a mathematical calculation called a "Wilson Score". The Ruby code he provides with explanation is as follows:

require 'statistics2'

def ci_lower_bound(pos, n, confidence)
    if n == 0
        return 0
    end
    z = Statistics2.pnormaldist(1-(1-confidence)/2)
    phat = 1.0*pos/n
    (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)
end

pos is the number of positive ratings, n is the total number of ratings, and confidence refers to the statistical confidence level: pick 0.95 to have a 95% chance that your lower bound is correct, 0.975 to have a 97.5% chance, etc. The z-score in this function never changes, so if you don't have a statistics package handy or if performance is an issue you can always hard-code a value here for z. (Use 1.96 for a confidence level of 0.95.)*

This would be a nice add to plusminus as a way to accurately measure popularity. I would volunteer, but I'm a part-time amateur at best, and no one (including me) would want my code going into production. (I'm a business person that does very basic MVPs.)

vote giving cannot convert symbol into an integer error

I need the ability to both vote up and vote down. I am using vote in this way :-

def vote_up
    begin
      current_user.vote(@post,:true)
      redirect_to [@topic.forum,@topic]
      flash[:success] = "You have voted successfully"
    rescue ActiveRecord::RecordInvalid
        redirect_to [@topic.forum,@topic]
        flash[:error] = "You have already voted for this one"
    end
end

when I click on the link to vote up i get the error cannot convert symbol into an integer. Am I using vote in a wrong manner?

Thanks,
Akram

Count plusminus_tally gives error (at least on PostgreSQL)

[1] pry(main)>  classifications = Classification.plusminus_tally
[2] pry(main)> classifications.count
   (0.5ms)  SELECT COUNT(*) AS count_all, classifications.id AS classifications_id FROM "classifications" LEFT OUTER JOIN votes ON classifications.id = votes.voteable_id AND votes.voteable_type = 'Classification' GROUP BY classifications.id ORDER BY plusminus_tally DESC
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "plusminus_tally" does not exist
LINE 1: ...ssification' GROUP BY classifications.id ORDER BY plusminus_...
                                                             ^
: SELECT COUNT(*) AS count_all, classifications.id AS classifications_id FROM "classifications" LEFT OUTER JOIN votes ON classifications.id = votes.voteable_id AND votes.voteable_type = 'Classification' GROUP BY classifications.id ORDER BY plusminus_tally DESC

A work-around is to convert to an array first (classifications.to_a.count), but shouldn't the AREL count work?

will_paginate breaks when tally or plusminus_tally is used

When using tally or plusminus_tally is used in a ActiveRelation it breaks the will_paginate page(params[:page]) or paginate(:page => params[:page]) methods.

I'm not sure who's at fault but I believe thumbs_up may be at fault the way the SQL is structured. If I run a regular relation asking for the count of records returned:

> Violation.without_spammed.order("created_at DESC").page(1).count
   (0.4ms)  SELECT COUNT(*) FROM "violations" WHERE "violations"."spammed" = 'f'
=> 4

And if I use the plusminus_tally in the line:

> Violation.without_spammed.plusminus_tally.reorder("created_at DESC").page(1).count
   (0.5ms)  SELECT COUNT(*) AS count_all, violations.id, violations.title, violations.description, violations.address, violations.violator_id, violations.created_at, violations.updated_at, violations.user_id, violations.slug, violations.flagged, violations.user_ip, violations.user_agent, violations.referrer, violations.spammed AS violations_id_violations_title_violations_description_violations_address_violations_violator_id_violations_created_at_violations_updated_at_violations_user_id_violations_slug_violations_flagged_violations_user_ip_violations_user_agent_violations_referrer_ FROM "violations" LEFT OUTER JOIN votes ON violations.id = votes.voteable_id AND votes.voteable_type = 'Violation' WHERE "violations"."spammed" = 'f' GROUP BY violations.id, violations.title, violations.description, violations.address, violations.violator_id, violations.created_at, violations.updated_at, violations.user_id, violations.slug, violations.flagged, violations.user_ip, violations.user_agent, violations.referrer, violations.spammed
=> {false=>1}

It appears to break what is expected: A result of 4. Please advise!

Environment:
Rails 3.2.11
thumbs_up 0.6.3
will_paginate 3.0.4

#karma does not subtract downvotes, only sums upvotes

I'm a bit confused here. Looking through older issues, bouchard states that karma gets calculated by taking the sum of the upvotes minus the sum of the downvotes.

Looking into this behavior in my application, I found this is not the case. When I went to look at the code in has_karma.rb, it looks like it just grabs all the votes where vote = true and never does anything with votes where vote = false.

def karma(options = {})
  self.class.base_class.karmic_objects.collect do |object, attr|
    v = object.where(["#{Vote.table_name}.vote = ?", true]).where(["#{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = ?", self.id])
    v = v.joins("INNER JOIN #{Vote.table_name} ON #{Vote.table_name}.voteable_type = '#{object.to_s}' AND #{Vote.table_name}.voteable_id = #{object.table_name}.#{object.primary_key}")
    v = v.joins("INNER JOIN #{self.class.base_class.table_name} ON #{self.class.base_class.table_name}.#{self.class.base_class.primary_key} = #{object.table_name}.#{attr[0]}")
    (v.count.to_f * attr[1]).round
  end.sum
end

Am I missing something? I feel like I'm reporting intended behavior, the only reason I say something is because I've read in previous issues that this shouldn't be the case.

Return vote record from :vote method for post-processing

I need to do things with the vote record after a vote is cast. The vote method uses create! which doesn't return the record.

Fortunately it doesn't appear that this is a specified requirement or expectation. Will submit PR.

Access votes_for in controller?

I'm likely missing something obvious?

user.rb:
class User < ActiveRecord::Base
attr_accessible :FirstName, :LastName, :password, :password_confirmation, :emailAddress
has_secure_password
has_many :locations, :through => :LocationsUsersXREF
has_and_belongs_to_many :organizations
acts_as_voter

end

topic.rb
class Topic < ActiveRecord::Base
attr_accessible :Name, :Description, :parent, :order, :entityOrdinal, :tag_list, :tags
belongs_to :event
acts_as_taggable
acts_as_voteable
end

topics_controller.rb:

class TopicsController < ApplicationController

def VoteCountFor
topicID = params[:topicID]
tmpTopic = Topic.where("id =?", topicID)
respond_to do |format|
format.html
format.xml {render :xml => tmpTopic.votes_for}
format.js {render :json => tmpTopic.votes_for}
end
end
end

ERROR when accessing: /topics/VoteCountFor/6.js

Topic Load (0.3ms) SELECT "topics".* FROM "topics" WHERE (id ='6')
Completed 500 Internal Server Error in 5ms

NoMethodError (undefined method votes_for' for #<ActiveRecord::Relation:0xb35772f0>): app/controllers/topics_controller.rb:99:inVoteCountFor'

plusminus_tally with Postgres on Heroku is unhappy

I'm coming from http://github.com/trevoke/dfworldgen - and I must say, as far as ease of use and ease of setup, I do so love this gem so far!

$ heroku run rails c
irb > ParameterSet.plusminus_tally
ParameterSet Load (10.9ms) SELECT parameter_sets., SUM(CASE CAST(votes.vote AS UNSIGNED) WHEN 1 THEN 1 WHEN 0 THEN -1 ELSE 0 END) AS plusminus_tally, COUNT(votes.id) AS vote_count FROM "parameter_sets" LEFT OUTER JOIN votes ON parameter_sets.id = votes.voteable_id GROUP BY parameter_sets.id ORDER BY plusminus_tally DESC
ActiveRecord::StatementInvalid: PG::Error: ERROR: type "unsigned" does not exist
LINE 1: ...ECT parameter_sets.
, SUM(CASE CAST(votes.vote AS UNSIGNED) ...
^
: SELECT parameter_sets.*, SUM(CASE CAST(votes.vote AS UNSIGNED) WHEN 1 THEN 1 WHEN 0 THEN -1 ELSE 0 END) AS plusminus_tally, COUNT(votes.id) AS vote_count FROM "parameter_sets" LEFT OUTER JOIN votes ON parameter_sets.id = votes.voteable_id GROUP BY parameter_sets.id ORDER BY plusminus_tally DESC
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1106:in async_exec' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1106:inexec_no_cache'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:650:in block in exec_query' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:280:inblock in log'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.1/lib/active_support/notifications/instrumenter.rb:20:in instrument' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:275:inlog'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:649:in exec_query' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1201:inselect'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/database_statements.rb:16:in select_all' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/query_cache.rb:63:inselect_all'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/querying.rb:38:in block in find_by_sql' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/explain.rb:40:inlogging_query_plan'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/querying.rb:37:in find_by_sql' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:170:inexec_queries'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:159:in block in to_a' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/explain.rb:40:inlogging_query_plan'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:158:in to_a' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:495:ininspect'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in start' from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:instart'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in <top (required)>' from script/rails:6:inrequire'
from script/rails:6:in `

'irb

Using plusminus_tally in a scope make db:migrate crash

First thank you for your plugin, it's awesome ;)
And keep maintaining it ! (I could help)

Sooo I stumbled upon this issue when trying to reinstall my app on another server :

I have a scope in my user.rb model :

scope :best, plusminus_tally.reorder("vote_total DESC")

which throws an error saying that "table users does not exist"

I added a :

unless File.basename($0) == 'rake' .... end

around it so everything is now working just fine.

But maybe it could be avoided ? I'm not quite comfortable with those Rails internals yet so I couldn't tell.

Cheers !

Does not work with PostgreSql

Tried to use thumbs_up on Heroku.com, which runs on a PostgreSql database. It fails with a message;

ActiveRecord::StatementInvalid (PGError: ERROR: column "vote_count" does not exist
LINE 1: ... = 'Photo') GROUP BY votes.voteable_id HAVING vote_count...
^
: SELECT photos.*, COUNT(votes.voteable_id) AS vote_count FROM "photos" LEFT OUTER JOIN votes ON photos.id = votes.voteable_id WHERE (votes.voteable_type = 'Photo') GROUP BY votes.voteable_id HAVING vote_count > 0 AND vote_count >= 1 ORDER BY vote_count DESC):

This is due to a limitation in PostgreSQL of not allowing aliases in the HAVING clause (if I'm correct). It can be solved by using the full COUNT statement.

However, we run into the next PostgreSql limitation - all filelds in the SELECT statement is also needed in the GROUP BY statement. It can be solved by extracting them from the AR object and just joining them together.

Thanks for a great gem,

Martin

How do I show or influence karma?

Hi, thanks for writing this...I am not sure how to calculate or display the karma for a voter. is there a way to add other activities for karma points?

Heroku deployment fails even with thumbs_up 0.5.5

I just updated the Gem, tried again to push:

   Installing thumbs_up (0.5.5)
   Gem::InstallError: thumbs_up requires RubyGems version >= 1.6.0. Try 'gem update --system' to update RubyGems itself.
   An error occured while installing thumbs_up (0.5.5), and Bundler cannot continue.
   Make sure that `gem install thumbs_up -v '0.5.5'` succeeds before bundling.

Missing Method - Return vote type

I think there is a missing method for returning the vote type (or at least I didn't find it)

Seems unreasonable to check voted_for? and voted_against? just to see what the model voted..

I'd expect voted_which_way? to return it, but I still need to use it twice (or even 3 times) to see if the user voted up, down or didn't vote.

Is there a method which will return the vote (true, false, nil) in one request?

thanks

undefined method `vote_for'

I am getting the no method error with for the my postscontroller.

This is the log file in case you need it :-

Started POST "/topics/1/posts/1/vote_up" for 127.0.0.1 at 2012-01-10 18:56:04 +0530
Creating scope :page. Overwriting existing method Post.page.
Processing by PostsController#vote_up as HTML
Parameters: {"authenticity_token"=>"L1FZ28iriXO6D2P1nwjUgaVdmqjeQNMlfOcCPWk2Y6o=", "topic_id"=>"1", "id"=>"1"}
�[1m�[36mUser Load (0.2ms)�[0m �[1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1�[0m
�[1m�[35mForem::Topic Load (0.2ms)�[0m SELECT "forem_topics".* FROM "forem_topics" WHERE "forem_topics"."id" = ? LIMIT 1 [["id", "1"]]
�[1m�[36mPost Load (0.2ms)�[0m �[1mSELECT "forem_posts".* FROM "forem_posts" WHERE "forem_posts"."id" = ? LIMIT 1�[0m [["id", "1"]]
Completed 500 Internal Server Error in 102ms

NoMethodError (undefined method vote_for' for #<User:0xb878d1c>): app/controllers/posts_controller.rb:6:invote_up

Thanks,
Akram

Review: Daily Votes

Hi Brady,
thank you for this great work. I appreciate it!

I just changed thumbs_up to a daily voteable version. It`s to less for a pull req but maybe useable for someone.
I added a new index field to hold only the day and used this field as a member of the validate scope and also inside the pg fk. WIll this have any impact on the tally performance or performance in general ?

this is the migration

class AddIndexVotesForDailyVoters < ActiveRecord::Migration
  def change
    #remove old fk we replace it with another version below
    remove_index :votes, :name => "fk_one_vote_per_user_per_entity"
    #add indexable field with day values- no hours, minutes or seconds
    add_column  :votes, 
                :day_created_at,
                :timestamp
    #add the new index additionally based on day_created_at
    add_index   :votes,
                ["voter_id", "voter_type", "voteable_id", "voteable_type", "day_created_at"], 
                :name => "fk_one_vote_per_user_per_entity_per_day", 
                :unique => true
  end
end

and that`s the part in vote.rb

class Vote < ActiveRecord::Base
 #...
  #day_created_at
  validates_uniqueness_of :voteable_id, :scope => [:voteable_type, :voter_type, :voter_id, :day_created_at]
  #added
  before_create :record_day_created_at
  def record_day_created_at
    self.day_created_at=DateTime.now.utc.midnight
  end
end

tally voteables with :at_least => 0

Hi there. Is there some way around having a minimum of 1 vote for the tally method? I'd like to show my list of items in highest order first, trailing with those with zero votes. Here's a sample of what i'm trying:

@feature_requests = FeatureRequest.tally(
{:at_least => 0 }
)

thanks!

Possible for user to change their vote?

I know I could probably just look, but I wouldn't even know where to start. The README states that there is only one vote per user. Does this also mean that a user can't change their vote. I could also just try this out but I figured I'd ask, since it may be something that could be updated in the README if it's already possible.

Tally Examples

Hi
Can you please provide some tally examples?

How do I sort my voteables by votes count / karma?

thanks

Ruby encoding issue

Hello,

just got into a problem installing the 0.4.3 version of the gem in a ruby 1.9.2 environment with bundler.

The error was:

/usr/local/lib/ruby/1.9.1/rubygems/specification.rb:519:in `normalize_yaml_input': invalid byte sequence in US-ASCII (ArgumentError)
    from /usr/local/lib/ruby/1.9.1/rubygems/specification.rb:479:in `from_yaml'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_input.rb:183:in `load_gemspec'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_input.rb:51:in `block in initialize'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_reader.rb:64:in `block in each'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_reader.rb:55:in `loop'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_reader.rb:55:in `each'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_input.rb:32:in `initialize'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_input.rb:17:in `new'
    from /usr/local/lib/ruby/1.9.1/rubygems/package/tar_input.rb:17:in `open'
    from /usr/local/lib/ruby/1.9.1/rubygems/package.rb:58:in `open'
    from /usr/local/lib/ruby/1.9.1/rubygems/format.rb:63:in `from_io'
    from /usr/local/lib/ruby/1.9.1/rubygems/format.rb:51:in `block in from_file_by_path'
    from /usr/local/lib/ruby/1.9.1/open-uri.rb:35:in `open'
    from /usr/local/lib/ruby/1.9.1/open-uri.rb:35:in `open'
    from /usr/local/lib/ruby/1.9.1/rubygems/format.rb:50:in `from_file_by_path'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/rubygems_integration.rb:100:in `spec_from_gem'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/source.rb:77:in `fetch'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/installer.rb:50:in `block in run'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/installer.rb:49:in `run'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/installer.rb:8:in `install'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/cli.rb:220:in `install'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/vendor/thor.rb:263:in `dispatch'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/lib/bundler/vendor/thor/base.rb:386:in `start'
    from /usr/local/lib/ruby/gems/1.9.1/gems/bundler-1.0.18/bin/bundle:13:in `<top (required)>'
    from /usr/local/bin/bundle:19:in `load'
    from /usr/local/bin/bundle:19:in `<main>'

The error only appears when you installed the gem via "gem install thumbs_up" (which seems to use the gem thumbs_up.gemspec file) and not if you installed it via bundler and the git parameter...

As far as I can see it seems to be related to the magic utf-8 comment in the thumbs_up.gemspec file... the utf-8 magic comment is in line four and should be in line one. If it is in line one I get no errors whatsoever.
According to http://blog.grayproductions.net/articles/ruby_19s_three_default_encodings the magic comment should either be in line one or line two if there is a shebang line present.

Govinda

Couldn't find Post with id=vote_up

Hi everyone,

I am new to ROR and I'm trying hard to solve the issue by going through all the stackoverflow and github pages, but I still couldn't find a solution to my problem. I hope you guys will help me out.

The issue is that after I implemented thumbs_up gem, I followed the instructions by Brady here:
http://stackoverflow.com/questions/4907744/clarification-on-how-to-use-thumbs-up-voting-gem-with-rails-3

But my view page will have an error message:
No route matches {:action=>"vote_up", :controller=>"posts", :id=>nil}

I have checked rake routes and the vote_up_post path is there, so I tried going to http://0.0.0.0:3000/posts/vote_up and this shows up:

ActiveRecord::RecordNotFound in PostsController#show
Couldn't find Post with id=vote_up

_Here is my views - index.html.erb_*
<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>

_posts_controller.rb_
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

_model - user.rb_

Include default devise modules. Others available are:

:token_authenticatable, :confirmable,

:lockable, :timeoutable and :omniauthable

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

Setup accessible (or protected) attributes for your model

attr_accessible :email, :password, :password_confirmation, :remember_me

attr_accessible :title, :body

acts_as_voter

_model - post.rb_
attr_accessible :title, :source, :description, :imageurl, :link

validates :title, presence: true, uniqueness:true, length: { maximum: 70 }
validates :source, presence: true, length: { maximum: 20 }
validates :description, presence: true, length: { maximum: 240 }
validates :imageurl, presence: true
validates :link, presence: true

default_scope order: 'posts.created_at DESC'

acts_as_voteable

_routes.rb_
devise_for :users

resources :posts do
member do
post :vote_up
end
end

devise_scope :user do
get "sign_in", :to => "devise/sessions#new"
get "sign_out", :to => "devise/sessions#destroy"
get "sign_up", :to => "devise/registrations#new"
end

resources :submissions

match '/submit', to: 'submissions#new'
match '/post', to: 'posts#new'

Sorry for asking such a stupid problem, would really appreciate help from you guys.

Voting without logging in?

Sorry, if this isn't the place to ask, I've searched for this question on stackoverflow and couldn't find an answer. Is there a way to vote on voteables without having to log in? Something like http://www.yourather.com where you can vote by just going to the site.

tally on Heroku with Postgres is unhappy (?)

Well this is just frustrating.

irb(main):016:0> ParameterSet.tally
ParameterSet Load (1.4ms) SELECT parameter_sets., COUNT(votes.id) AS vote_count FROM "parameter_sets" LEFT OUTER JOIN votes ON parameter_sets.id = votes.voteable_id GROUP BY parameter_sets.id ORDER BY vote_count DESC
ActiveRecord::StatementInvalid: PG::Error: ERROR: column "parameter_sets.name" must appear in the GROUP BY clause or be used in an aggregate function
: SELECT parameter_sets.
, COUNT(votes.id) AS vote_count FROM "parameter_sets" LEFT OUTER JOIN votes ON parameter_sets.id = votes.voteable_id GROUP BY parameter_sets.id ORDER BY vote_count DESC
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1106:in async_exec' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1106:inexec_no_cache'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:650:in block in exec_query' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:280:inblock in log'
from /app/vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.1/lib/active_support/notifications/instrumenter.rb:20:in instrument' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract_adapter.rb:275:inlog'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:649:in exec_query' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/postgresql_adapter.rb:1201:inselect'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/database_statements.rb:16:in select_all' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/connection_adapters/abstract/query_cache.rb:63:inselect_all'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/querying.rb:38:in block in find_by_sql' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/explain.rb:40:inlogging_query_plan'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/querying.rb:37:in find_by_sql' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:170:inexec_queries'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:159:in block in to_a' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/explain.rb:40:inlogging_query_plan'
from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation.rb:158:in to_a' from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.1/lib/active_record/relation/delegation.rb:37:inmethod_missing'
from (irb):16
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in start' from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:instart'
from /app/vendor/bundle/ruby/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in <top (required)>' from script/rails:6:inrequire'
from script/rails:6:in `

'irb(main):017:0>

:conditions option for :plusminus_tally (rank_tally) missing

Hello, I'm just using your gem, and tried out tally like so...
Answer.tally(:conditions => "( answers.question_id = 5 )" )
works beautifully!

Then I tried
Answer.plusminus_tally( :conditions => "( answers.question_id = 5 )" )
it completely ignored my condition! I looked into your current source code, and discovered the option is missing from the plusminus_tally code.

Can you please correct??

Thanks

thumbs_up 0.5.0 requires Rubygem >= 1.8.10 on Heroku

Hi,

I'm using thumbs_up for my app but I can't push to Heroku, it says:

       Installing thumbs_up (0.5.0) Unfortunately, a fatal error has occurred. Please report this error to the Bundler issue tracker at https://github.com/carlhuda/bundler/issues so that we can fix it. Thanks!
       /usr/local/lib/ruby/1.9.1/rubygems/installer.rb:170:in `install': thumbs_up requires RubyGems version >= 1.8.10. Try 'gem update --system' to update RubyGems itself. (Gem::InstallError)
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/source.rb:90:in `block in install'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/rubygems_integration.rb:82:in `preserve_paths'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/source.rb:89:in `install'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:73:in `block in install_gem_from_spec'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/rubygems_integration.rb:97:in `with_build_args'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:72:in `install_gem_from_spec'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:56:in `block in run'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:55:in `run'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/installer.rb:12:in `install'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/cli.rb:220:in `install'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/task.rb:22:in `run'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor.rb:263:in `dispatch'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/lib/bundler/vendor/thor/base.rb:386:in `start'
       from /tmp/build_3epr7k3z94asr/vendor/bundle/ruby/1.9.1/gems/bundler-1.1.rc.7/bin/bundle:13:in `<top (required)>'
       from vendor/bundle/ruby/1.9.1/bin/bundle:19:in `load'
       from vendor/bundle/ruby/1.9.1/bin/bundle:19:in `<main>'
 !
 !     Failed to install gems via Bundler.
 !
 !     Heroku push rejected, failed to compile Ruby/rails app

I'm using Cedar stack.

This is my local environment:

  • Ruby 1.9.3-p69
  • Rails 3.2.1
  • RVM 1.6.2
  • thumbs_up 0.5.0

I found this one and this one but I think they are just workaround, I need thumbs_up in production.

Any idea? Thanks!

feature request - adding anonymous voting

I'm not sure how to navigate the gem to add it myself, but basically what should be added is another column for anonymity which defaults to false.

and then the ability to pass a parameter while voting if anonymity is true or false.

by anonymous I mean that the vote still requries a user to vote, but it will test whether the user wants that the vote will be displayed or not

dependant => destroy instead of nullify on has_many votes

In the ActsAsVoteable module,
I think the line
has_many :votes, :as => :voteable, :dependent => :nullify
should be
has_many :votes, :as => :voteable, :dependent => :destroy

If the association nullifies, i get an error like
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry '1-User-0-Suggestion' for key 'uniq_one_vote_only': UPDATE votes SET voteable_id = NULL WHERE ((voteable_id = 2) AND (voteable_type = 'Suggestion'))
when i try to destroy a suggestion.

The case is, I have 2 suggestions where a user voted and want to destroy them
The first one destroys ok, but as the votes table was defined "voteable_id int(11) null false" it sets to 0
When the second one is destroyed, same it also wants to put voteable_id to null (really 0), and then it raises that unique index error.

Let me know if there's a reason why this was implemented with nullify instead of destroy

ERROR: column votes.[voteable]_id does not exist

I'm trying to use thumbs_up, and I'm running into an issue I'd like to get some help with:

I have posts that are voteable
and users that are voters

The app wants to access vote.post_id when it calculates the votes_for, votes_against, or plusminus, and I get a column votes.post_id does not exist.

I've tried this with sqlite and postgresql, and I get the same error.

I've done the
rails generate thumbs_up
rake db:migrate

Do you have any idea what I've done wrong?

I have a class post that is voteable:

class Post < ActiveRecord::Base
acts_as_voteable

attr_accessible :description, :title, :url

belongs_to :user #foreign key - user_id

has_many :votes

end

and a User that can vote

class User < ActiveRecord::Base
acts_as_voter

has_karma(:posts, :as => :submitter, :weight => 0.5)

Include default devise modules. Others available are:

:token_authenticatable, :confirmable,

:lockable, :timeoutable and :omniauthable

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

Setup accessible (or protected) attributes for your model

attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :auth_token

has_many :posts
has_many :votes, :through => :posts

validates_presence_of :username
validates :password, :presence => FALSE

attr_accessible :title, :body

end

I can add positive and negative votes, but when I try to access the vote count I get this error:

Showing /app/views/posts/index.html.erb where line #24 raised:

PG::Error: ERROR: column votes.post_id does not exist
LINE 1: SELECT COUNT() FROM "votes" WHERE "votes"."post_id" = 1 AN...
^
: SELECT COUNT(
) FROM "votes" WHERE "votes"."post_id" = 1 AND "votes"."vote" = 't'

/app/views/posts/index.html.erb
...
21 <%= link_to image_tag(upimage, :border => 0), :controller => "posts", :id=> post.id, :action => "upvote", :remote => true %>
22
23


24 <%= post.votes_for %>
25

26

27 <%= link_to image_tag(downimage, :border => 0), :controller => "posts", :id=> post.id, :action => "downvote", :remote => true %>
28

...

Here are some relevant versions:
rails (3.2.11)
actionmailer (= 3.2.11)
actionpack (= 3.2.11)
activerecord (= 3.2.11)
activeresource (= 3.2.11)
activesupport (= 3.2.11)
bundler (> 1.0)
railties (= 3.2.11)
thumbs_up (0.6.4)
activerecord
statistics2
activemodel (3.2.11)
activesupport (= 3.2.11)
builder (
> 3.0.0)
activerecord (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
arel (> 3.0.2)
tzinfo (
> 0.3.29)
activeresource (3.2.11)
activemodel (= 3.2.11)
activesupport (= 3.2.11)
activesupport (3.2.11)
i18n (> 0.6)
multi_json (
> 1.0)
arel (3.0.2)
orm_adapter (0.4.0)
pg (0.15.1)
statistics2 (0.54)

How do I find the karma for a voter?

How can I find the karma for a voter? Are there ways for me to adjust the karma based on non-voting activity?

For example, we may know additional information about the user and want to add to their karma points.

undefined local variable or method 'acts_as_voteable' for...

Hi, thanks for your great work.

I currently have problem with some error only if I deploy with caspitrano to my ubuntu server.

I use nginx + unicorn in my deploy server and always shows me "undefined local variable or method 'acts_as_voteable' for..."

Strange thing is when I use local rails server there is no problem(mac book with rails 3.2.7 and same ruby 1.9.3 version)

The error only shown in deploy server. I checked installed bundle(thumbs_up) with bundle list command and also checked database table exist correctly in deploy server side.

Do you have any idea to solve this issue? or just advise me.

I'm first at ruby on rails and nginx+unicorn. So this might be my configuration problem.

Thanks,
Wooram

column "plusminus_tally' doesn't exist

@Items = Item.plusminus_tally.limit(10).where('created_at > ?', 2.days.ago).having('plusminus_tally > 10')

When i try to run the above command in my controller i get that said error. At first i tried the above command then changed to this command.

@Items = Item.plusminus_tally.limit(10).where('items.created_at > ?', 2.days.ago).having('plusminus_tally > 10')

The first command gave an ambiguous column error while the seond command gave: column 'plusminus_tally' doesnt exist. Regards

Sorting doesn't seem to be working with plusmins_tally

Given the following:

    @videos = Video.plusminus_tally({
      :order => "votes.count DESC"})

I noticed that if I change this to ASC nothing changes when I refresh the page. I went as far as to try to sort by name, etc, and no ordering changed. I even tried making it go blank and nothing. So, I'm pretty sure that ordering is never actually hit and it's only a hard value. Bug?

Votable id broken and other fields too with the new tally

1.8.7 :018 > Talk.all.last
  Talk Load (0.2ms)  SELECT "talks".* FROM "talks" 
 => #<Talk id: 10, title: "più votato", content: "dwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfd...", status: "hidden", user_id: 2, created_at: "2012-02-23 15:49:20", updated_at: "2012-02-23 15:49:20"> 
1.8.7 :019 > Talk.tally.all.last
  Talk Load (0.6ms)  SELECT talks.*, votes.*, COUNT(votes.id) AS vote_count FROM "talks" LEFT OUTER JOIN votes ON talks.id = votes.voteable_id GROUP BY talks.id ORDER BY vote_count DESC
 => #<Talk id: nil, title: "più votato", content: "dwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfdwfwfd...", status: "hidden", user_id: 2, created_at: nil, updated_at: nil>

How can I add a new "status" (e.g. up, down,..)

I need to allow my users to vote up, down or neutrally.

I can't just remove all the votes and consider it neutral because that way I will lose track of the ones that have been voted neutrally.

Thank you very much, if the customization is fairly simple I will be happy to post the code after I get it working, should you or anyone else need it.

How can I tell whether a voter voted plus or minus?

Right now, it looks like I can only tell if a voter voted on a voteable. But I can't tell whether the vote was a plus or a minus.

How do I do that? I need to know so that when I have "arrows" showing vote, I can show how a user voted.

wrong number of arguments (2 for 1)

I'm getting:

  wrong number of arguments (2 for 1)

When I do:

  @posts = Post.tally({
      :at_least => 1,
      :start_at => 2.weeks.ago,
      :end_at => 1.day.ago,
      :order => "votes.count DESC"
  })

Rails 3.0.3, Ruby 1.8.7. Any ideas?

Karma count doesn't use default scope for Vote model

I added a 'deleted_at' column on my voteable model as well as to the Votes table to allow for soft deletion.

Using a default scope on the Vote model (like this default_scope where(:deleted_at => nil)) seems to work for most of the thumbs_up methods (by not counting votes with deleted_at values). Unfortunately it doesn't seem to work for the karma calculation.

Do you have any plans or advice for modifying this gem to correctly honor the default_scope in all cases?

Nice work. Join forces?

I think you did a great job with this re-write / upgrade / improvement. I'd like to clean up the cruft of having the old VoteFu Rails 2 project hanging around. I've also been looking at folding a lot of the open forks back in to VoteFu, since a lot of people are solving the same problems in their forks.

Seems like a good opportunity to consolidate some effort and have everyone reap the benefits.

After reintegrating common bugfixes and feature from the various forks, I was most interested in adding great test coverage to VoteFu, and making it work as an Engine so that you don't have to copy stuff around into client applications to make it work.

Interested in sharing efforts?

--Pete

Wilson Score method ranking

There seems to be no method to tally all voteables (as in plusminus_tally) based on Wilson Score method (ci_plusminus). Am I missing something?

plusminus_tally doesn't join on voteable_type

Giving a look at the plusminus_tally generated query, I discovered that it doesn't join on the voteable_type field, so vote count are not correct when you have more than one type of voteable objects.

You should edit the first line of the method definition:

  def plusminus_tally(params = {})
   t = self.joins("LEFT OUTER JOIN #{Vote.table_name} ON #{self.table_name}.id = #{Vote.table_name}.voteable_id")
    t = t.order("plusminus_tally DESC")
    t = t.group("#{self.table_name}.id")
    t = t.select("#{self.table_name}.*")
    t = t.select("SUM(CASE CAST(#{Vote.table_name}.vote AS UNSIGNED) WHEN 1 THEN 1 WHEN 0 THEN -1 ELSE 0 END) AS plusminus_tally")
    if params[:separate_updown]
      t = t.select("SUM(CASE CAST(#{Vote.table_name}.vote AS UNSIGNED) WHEN 1 THEN 1 WHEN 0 THEN 0 ELSE 0 END) AS up")
      t = t.select("SUM(CASE CAST(#{Vote.table_name}.vote AS UNSIGNED) WHEN 1 THEN 0 WHEN 0 THEN 1 ELSE 0 END) AS down")
    end
    t = t.select("COUNT(#{Vote.table_name}.id) AS vote_count")
  end

vote_exclusively_for/against issue

I'm currently using the thumbs_up gem to allow my users to vote on posts and am having an issue with the vote_exclusively_for/against methods. The gem works fine with the vote_up and vote_down methods, but when I change it to vote_exclusively_for (which is supposed to replace a previous down vote w/ an up vote), I get the following error in my development log:

ActiveRecord::RecordInvalid (Validation failed: Voteable has already been taken):
app/controllers/posts_controller.rb:97:in `vote_up'

Here's my code in the posts_controller:

def vote_up
@user = current_user
@post = Post.find(params[:id])
@user.vote_exclusively_for(@post)
redirect_to (..)
end

Here's the code from the acts_as_voter.rb file from the gem:

def vote_exclusively_for(voteable)
self.vote(voteable, { :direction => :up, :exclusive => true })
end

def vote(voteable, options = {})
raise ArgumentError, "you must specify :up or :down in order to vote" unless options[:direction] && [:up, :down].include?(options[:direction].to_sym)
if options[:exclusive]
self.clear_votes(voteable)
end
direction = (options[:direction].to_sym == :up)
Vote.create!(:vote => direction, :voteable => voteable, :voter => self)
end

def clear_votes(voteable)
Vote.where(
:voter_id => self.id,
:voter_type => self.class.name,
:voteable_id => voteable.id,
:voteable_type => voteable.class.name
).map(&:destroy)
end

It appears that in my case the clear_votes method is not deleting the previous vote by the user. Any help would be greatly appreciated.

Thanks,

Mike

Thanks for your excellent job

Hi friend, you really did a great job, but can you add a feature of a maximum of 30 votes can be cast per user per day?
Thank you very much.

Views problems

Bouchard, I love this gem but man did I spend a long time just getting a completely standard implementation up and running. The main problem was the views.

Why not create a <%= acts_as_voteable @post %> partial for the view that has the standard interactions. It could take the arguments :remote => true to make it ajaxy.

Also some snippets of controller code that work with the partial (like below - but with unobtrusive javascript built) in would be REALLY useful getting off the ground.

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.