2014-10-18 40 views
1

我正在设置我的投票系统,并试图建立一个帮手模型,以便我可以检查用户是否投了票。我是新来的铁路,似乎无法找出这一个。如何获取Rails 4如果记录有两个条件返回true否则为false?

我该如何对user_idcurrent_usercard_id的记录进行模型检查投票?

我也试图通过设置voted变量来限制每次迭代_cards.html.erb多次调用助手。不知道如何做到这一点,试图设置变量只是为每张卡片打印真实,即使是没有投票的卡片。

设置变量不起作用,既不是助手,因为它总是如此。

cards_controller.rb

def if_voted(card_id) 
    if Vote.where(:user_id => current_user.id, :card_id => card_id) then 
    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> 

随着@tadman的帮助

cards_controller.rb

def if_voted(card_id) 
    if Vote.where(:user_id => current_user.id, :card_id => card_id).any? then 
    @vote = Vote.find_by(:user_id => current_user.id, :card_id => card_id) 
    return @vote.voted 
    else 
    return 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> 

谢谢

回答

4

where方法总是返回,即使该范围不包含任何记录的范围。 find_by方法使用相同的选项,但返回第一个匹配记录或nil,如果没有找到。

虽然这并不完全是你想要的。您实际上并不想检索任何记录,而只是检查它们是否存在。如果存在一个或多个记录,则范围上的any?方法为true,否则为false

你应该更新你的代码看起来像这样:

def if_voted(card_id) 
    Vote.where(:user_id => current_user.id, :card_id => card_id).any? 
end 

值得一提的关于你的Ruby风格的几件事情:

  • 使用thenif条款的结束,同时支持,是无关的,通常没有完成。
  • 比较东西== true通常表示您的逻辑混乱。如果你关心的是true而不仅仅是逻辑上的真实,请改用=== true。在这种情况下,需要足够的计数,因此if (if_voted(...))就足够了。
  • 您的方法返回了truefalse,但您有三个条件,就好像您期待maybe有一天会弹出一样。
  • if_voted这样的方法名称有点笨拙,尤其是在if中使用时。类似于has_voted?更符合一般的Ruby和Rails,所以你得到if (has_voted?(...)),它读得好多了。
  • 更好的办法是将此方法迁移到User类中,以便您可以消除帮助者,并以if (current_user.has_voted?(card_id))作为表达意图的非常明确的方式。
相关问题