2013-10-14 163 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