[英]How do I write this conditional statement for a nested resource in rails?
I have three models: User Poll PollItem Vote我有三个模型: User Poll PollItem Vote
A user has many polls and votes一个用户有很多投票和投票
Poll has many poll items(nested attributes) and belongs to user投票有很多投票项目(嵌套属性)并且属于用户
Poll item has many votes and belongs to poll投票项目有很多票,属于投票
Votes belong to poll item and User投票属于投票项目和用户
I already made a voting feature where a user can vote/unvote poll items.我已经做了一个投票功能,用户可以投票/取消投票项目。 Now, I am trying to write a conditional statement so that a user will be able to vote on just a poll item within a poll.
现在,我正在尝试编写一个条件语句,以便用户能够对投票中的投票项目进行投票。 For example, if a vote has already been recorded for the first poll item within a poll then I want the vote link be disabled on other poll items within the poll except for the one voted on.
例如,如果已经为投票中的第一个投票项目记录了投票,那么我希望在投票中的其他投票项目上禁用投票链接,除了已投票的投票项目。
<% if current_user.votes.where(poll: @poll).count > 0 %>
display vote link
<% else %>
remove vote link
<% end %>
But I get the error SQLite3::SQLException: no such column: votes.poll_id但我收到错误 SQLite3::SQLException: no such column: votes.poll_id
Please suggest a better title to the question too.请也为这个问题提出一个更好的标题。
EDIT:编辑:
As suggested by @lam, I adjusted the statement to正如@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 %>
However, the action got performed on all the poll items in a poll.但是,该操作已在投票中的所有投票项目上执行。 When I voted on a poll item, the vote links on other poll items changed instead of the voted item.
当我对投票项目进行投票时,其他投票项目的投票链接发生了变化,而不是投票项目。
if Votes belong to poll item and User
then the Vote should has poll_item_id
, not poll_id
.如果
Votes belong to poll item and User
那么投票应该有poll_item_id
,而不是poll_id
。 So i guess the logic like this:所以我猜逻辑是这样的:
<% 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.