如何为rails中的嵌套资源编写此条件语句



我有三个模型:用户投票项目投票

一个用户有许多投票和投票

轮询有许多轮询项目(嵌套属性(,属于用户

投票项目有许多选票,属于投票

投票属于投票项目和用户

我已经做了一个投票功能,用户可以投票/取消投票项目。现在,我正在尝试编写一个条件语句,这样用户就可以在投票中只对一个投票项目进行投票。例如,如果投票中的第一个投票项目已经记录了投票,那么我希望投票中除投票项目外的其他投票项目的投票链接被禁用。

<% if current_user.votes.where(poll: @poll).count > 0 %>
display vote link
<% else %>
remove vote link
<% end %>

但我弄错了SQLite3::SQLException:没有这样的列:votes.poll_id

也请为这个问题提出一个更好的标题。

编辑:

根据@lam的建议,我将声明调整为

<% if user_signed_in? && Vote.where(user_id: current_user.id).where(poll_item_id: @poll.poll_items.pluck(:id)).count > 0 %>
<p>You have voted</p>
<%= link_to "Unvote", poll_poll_item_vote_path(@poll, @poll_item), method: :delete %>
<% else %>
<%= link_to "Vote", poll_poll_item_vote_path(@poll, @poll_item), method: :post %>
<% end %>

但是,该操作已在一个轮询中的所有轮询项目上执行。当我对某个投票项目进行投票时,其他投票项目的投票链接会发生更改,而不是已投票项目。

如果是Votes belong to poll item and User,那么投票应该是poll_item_id,而不是poll_id。所以我猜逻辑是这样的:

<% if user_signed_in? && Vote.where(user_id: current_user.id, poll_item_id: @poll_item.id).count > 0 %>
<p>You have voted</p>
<%= link_to "Unvote", poll_poll_item_vote_path(@poll, @poll_item), method: :delete %>
<% else %>
<%= link_to "Vote", poll_poll_item_vote_path(@poll, @poll_item), method: :post %>
<% end %>

最新更新