Reputation: 347
I'm trying to calculate a conversion rate. However I've only been able to get it working using
User.first
however I don't really want the first user, as my app can have many. I want the specific user that is currently signed in to be that user.
Here's how the conversion rate method looks (campaign belongs to user):
campaign.rb
def conversion_rate
fav = self.favorites.where(favorited: true)
val = fav.present? ? self.favorites.where(:owner_id => User.first.followers.map(&:follower_id)).count.to_f / fav.count.to_f * 100 : 0.0
val
end
what's the right method after the User here in order to find the actual user?
Upvotes: 1
Views: 23
Reputation: 340
Basically, you want to get the user's ID from the current session. The details of this will vary based on how you've implemented user authentication and so on, but in general when a user logs in they'll get a session ID from your application that will be stored locally in their browser and used to track their actions while logged in. This ID is generally accessible through something like session[:user_id]
in your application, enabling you to get the currently-logged-in user through something like User.find(session[:user_id])
. See http://guides.rubyonrails.org/security.html#sessions for more information on this. Also, if you're using an authentication library (like Devise or something), check in its documentation for information on how it handles sessions.
Upvotes: 0
Reputation: 47548
The conversion_rate
method depends on a user. You can pass that into the method as an argument:
def conversion_rate(user)
fav = self.favorites.where(favorited: true)
val = fav.present? ? self.favorites.where(:owner_id => user.followers.map(&:follower_id)).count.to_f / fav.count.to_f * 100 : 0.0
val
end
Then it is only a matter of getting the currently logged in user. This depends on your application, but a typical Rails app has a current_user
method defined in ApplicationController. You would have to call the conversion_rate
method at a point in your code where current_user
is available, i.e. in a controller action.
Upvotes: 0
Reputation: 2575
So I think you have current_user
in your application_controller
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
then this will be accessible in all controllers and views
So you can call @campaign.conversion_rate(current_user)
, and pass current_user
def conversion_rate(user)
fav = self.favorites.where(favorited: true)
val = fav.present? ? self.favorites.where(:owner_id => user.followers.map(&:follower_id)).count.to_f / fav.count.to_f * 100 : 0.0 val
end
Upvotes: 1