0

我有一个模型组 -> has_many :questions 和一个问题 -> has_many :votes

在我的视图显示中,对于控制器组,我有一个可以显示问题列表的部分: <%= render :partial => 'question', :collection => @group.questions.byvote %> 然后我有一个链接可以用这样的样式投票:

<%= link_to(question_votes_path(question), :controller => :vote, :action => :create, :method => :post, :id => 'vote') do %>
<%= image_tag("voteUp.png")%>
<%= question.votes_count%>
<%end%>

我想做的是做一个条件,比如:

    <% if canvote?%>

... 并更改 div 的样式。

但。无法在组控制器中设置条件,因为我需要就问题而不是组提出请求:

Vote.where(:user_id => current_user.id, :question_id => @question.id).first

我怎样才能使它形成另一个控制器组或告诉问题控制器中的 helper_method ?

4

1 回答 1

1

我认为您应该使用模型方法 - 然后您可以在视图中直接调用它并且不显眼地这样做。true如果用户对给定的 投票,则以下方法将返回question

用户.rb

def voted?(question)
  #returns true if vote exists
  Vote.exists?(:user_id => current_user.id, :question_id => question.id) 
end

你可以像这样使用它:

_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 %>
于 2013-10-14T08:28:44.807 回答