繁体   English   中英

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

[英]How do I write this conditional statement for a nested resource in rails?

我有三个模型: User Poll PollItem Vote

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

投票有很多投票项目(嵌套属性)并且属于用户

投票项目有很多票,属于投票

投票属于投票项目和用户

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

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

但我收到错误 SQLite3::SQLException: no such column: 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 %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM