Reputation: 253
I have a model group -> has_many :questions and a question -> has_many :votes
In my my view show, for the controller groups, I have a partial that can display the list of the questions :
<%= render :partial => 'question', :collection => @group.questions.byvote %>
Then I have a link to vote with a style like this :
<%= link_to(question_votes_path(question), :controller => :vote, :action => :create, :method => :post, :id => 'vote') do %>
<%= image_tag("voteUp.png")%>
<%= question.votes_count%>
<%end%>
What I would like to do is make a condition, like :
<% if canvote?%>
… and change the style of the div.
BUT. Making a condition in the group controller can't be made because I need to make my request about the question and not about the group :
Vote.where(:user_id => current_user.id, :question_id => @question.id).first
How can I make it form the other controller group or tell an helper_method in the question controller ?
Upvotes: 0
Views: 49
Reputation: 10997
I think you should use a model method - you can then call it right in the view and do so unobtrusively. The following method will return true
if the user has voted on a given question
:
User.rb
def voted?(question)
#returns true if vote exists
Vote.exists?(:user_id => current_user.id, :question_id => question.id)
end
You can use it like this:
_question.html.erb
<% if current_user.voted?(@question) %>
#code to use if the user has voted on this question
<% else %>
#code to use if the user has NOT voted on this question
<% end %>
Upvotes: 1