Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a method that return true or false based on a record count

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

like image 253
AnApprentice Avatar asked Feb 24 '23 18:02

AnApprentice


2 Answers

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.

like image 164
DigitalRoss Avatar answered Feb 26 '23 06:02

DigitalRoss


This should be a pretty efficient method:

def has_user_voted?(user)
  self.poll_votes.exists?(['user_id = ?', "%#{user.id}%"])
end
like image 35
Luke Avatar answered Feb 26 '23 07:02

Luke