我正在设置投票系统,并尝试建立一个助手模型,以便可以检查用户是否对卡片进行了投票。我是Rails的新手,似乎无法弄清楚这一点。
如何对具有创纪录的模型支票票user_id
的current_user
和card_id
?
我还试图_cards.html.erb
通过设置voted
变量来限制每次调用多次的帮助程序。不确定如何执行此操作,尝试设置变量只是为每张卡(即使没有投票的卡)打印true。
设置变量不起作用,帮助程序也不起作用,因为它始终是正确的。
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>
谢谢
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风格的几件事:
then
在if
受支持的情况下,在子句的末尾使用是多余的,通常不会这样做。== true
通常是您的逻辑混乱的标志。如果您担心某些东西是文字上的true
而不是逻辑上正确的,请=== true
改用。在这种情况下,足够多的计数if (if_voted(...))
就足够了。true
或,false
但是您有三个条件,就像您希望maybe
一天弹出一样。if_voted
有些笨拙,尤其是在内使用时if
。has_voted?
一般而言,类似的东西与Ruby和Rails更加相符,因此您得到if (has_voted?(...))
的东西读起来要好得多。User
类中,这样您就可以消除帮助程序,并最终以if (current_user.has_voted?(card_id))
一种非常清晰的方式表达您的意图。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句