postgresql - How to get Rails 4 if a record has two conditions return true else false? -
postgresql - How to get Rails 4 if a record has two conditions return true else false? -
i'm setting vote system, , trying have helper model can check if user has voted card. i'm new rails , can't seem figure 1 out.
how have model check votes record has user_id
of current_user
, card_id
?
i'm trying limit calling helper many times each iteration of _cards.html.erb
setting voted
variable. not sure how this, trying set variable printing true every card, ones have no votes.
setting variable not working , neither helper, true.
cards_controller.rb:
def if_voted(card_id) if vote.where(:user_id => current_user.id, :card_id => card_id) true else false end end helper_method :if_voted
_cards.html.erb:
<td> <%= @voted = if_voted(card.id) %> <% if @voted == true %> <span class="green"><center> <% elsif @voted == false %> <span class="red"><center> <% else %> <span class="gray"><center> <% end %> <%= card.up_votes - card.down_votes %> </center></span> </td>
with help of @tadman
cards_controller.rb
def if_voted(card_id) if vote.where(:user_id => current_user.id, :card_id => card_id).any? @vote = vote.find_by(:user_id => current_user.id, :card_id => card_id) homecoming @vote.voted else homecoming nil end end helper_method :if_voted
_cards.html.erb
<td> <% @voted = if_voted(card.id) %> <% if @voted == true %> <span class="green"><center> <% elsif @voted == false %> <span class="red"><center> <% else %> <span class="gray"><center> <% end %> <%= card.up_votes - card.down_votes %> </center></span> </td>
thank you
the where
method returns scope if scope not contain records. find_by
method uses same options returns either first matching record or nil
if none found.
that's not quite want here, though. don't want retrieve of records, instead check if exist. any?
method on scope true
if 1 or more records exist, or false
otherwise.
you should update code this:
def if_voted(card_id) vote.where(:user_id => current_user.id, :card_id => card_id).any? end
it's worth noting few things ruby style:
usingthen
@ end of if
clause, while supported, extraneous , not done. comparing things == true
sign logic confused. if you're concerned beingness literal true
rather logically true, utilize === true
instead. in case, close plenty counts, if (if_voted(...))
should suffice. your method returned either true
or false
had 3 conditions if expecting maybe
pop 1 day. method names if_voted
little clumsy, if used within if
. has_voted?
much more in line ruby , rails in general, if (has_voted?(...))
reads lot better. even improve migrate method user
class can eliminate helper , end if (current_user.has_voted?(card_id))
clear way of expressing intent. ruby-on-rails postgresql helper
Comments
Post a Comment