简体   繁体   中英

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

I have three models: 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

Please suggest a better title to the question too.

EDIT:

As suggested by @lam, I adjusted the statement to

<% 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 . 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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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