Reputation: 343
How can i get a percentage of how many users favorited a post? So something like 80% of users favorite the first post. I am also using a gem called Markable.
In my posts controller i can favorite a post like this.
class PostsController < ApplicationController
def favorite
@post = Post.friendly.find(params[:id])
current_user.mark_as_favorite @post
redirect_to @post
end
end
I can see all the users who have favorited a post like this
@post = Post.first << Test post
@post.users_have_marked_as_favorite << [user1, user2]
@post.users_have_marked_as_favorite.count << 2
Below are my Post and User models
class Post < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: :slugged
# the markable_as :favorite is what gives me the option to favorite
markable_as :favorite
end
class User < ActiveRecord::Base
acts_as_marker
end
Upvotes: 0
Views: 55
Reputation: 42799
This will calculate the percentage and round it to only have 2 decimal numbers
class Post < ActiveRecord::Base
def favored_percentage
(users_have_marked_as_favorite.count * 100 / User.count).round(2)
end
end
Upvotes: 1