开发者

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?(curr开发者_如何转开发ent_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 just want to know if there are any matching records you should use the built-in count method instead of needlessly retrieving a bunch of rows and instantiating all those objects. e.g.:

def has_user_voted? user
  poll_votes.where(:user_id => user.id).count > 0
end


Another slight technicality to note:

def has_user_voted? user poll_votes.where(:user_id => user.id).size > 0 end

.size will either issue a db .count, or if the association is already loaded, it will get the length of the array and not even do a sql call. I always use size.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜