2013-10-14 165 views
0

我有一个模型组 - >的has_many:问题,并在一个问题 - >的has_many:票条件从其他控制器

以我我的视图显示,用于控制器组,我有一个部分,可以显示的的问题清单: <%= 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问题控制器?

+0

“canvote?”理想地告诉你什么?用户可以投票的条件是什么? – dax

+0

它告诉我是否存在一个来自current_user的记录“投票”的问题。 – Rufilix

回答

1

我认为你应该使用模型方法 - 然后你可以在视图中调用它,并且不显眼地进行。下面的方法将返回true如果用户已经投票给定question

User.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 %> 
+0

谢谢!完美工作。我只需在模型中添加'current_user = UserSession.find.user'。 – Rufilix

+0

太棒了,很高兴它的工作:)你也可以使用':user_id => self.id' – dax

+0

不错。 Thx再次! – Rufilix