I'm trying to create a method that return either true or false.
Here is what I have
View
<%= @poll.has_user_voted?(current_user) %>
Model
def has_user_voted?(user)
voted = self.poll_votes.where(:user_id => user.id).length
return !voted
end
Any idea what I'm doing wrong. It's returning nothing blank
Everything is true in Ruby except nil
and false,
which means that 0
is actually true.
Try something like:
def has_user_voted?(user)
self.poll_votes.where(:user_id => user.id).length > 0
end
This is just an example, I presume that you also want the vote so your real-life version will make use of poll_votes,
if not, you might want to just use #count
.
This should be a pretty efficient method:
def has_user_voted?(user)
self.poll_votes.exists?(['user_id = ?', "%#{user.id}%"])
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With