2011-04-14 40 views
0

我是新來的Rails,我想知道我是否可以重構下面的代碼。Rails 3 - Ajax和控制器重構

基本上我想爲ajax中的問題vote_down ou vote_up。

控制器:

def vote_up 
@question = get_question params[:id] 
if current_user != @question.user 
    render :json => @question.vote(current_user, 'up').to_json 
end 
end 

def vote_down 
@question = get_question params[:id] 
if current_user != @question.user 
    render :json => @question.vote(current_user, 'down').to_json 
end 
end 

型號:

def vote(user, vote) 
if user.voted?(self) 
    'Question already voted' 
else 
    I18n.t('question.voted') if user.send("#{vote}_vote", self) 
end 
end 

查看:

<script> 
$('#question_vote_up').live('ajax:success', function(evt, data, status, xhr) { 
$('#question_vote_up').remove() 
$('#question_vote_down').remove() 
alert(xhr.responseText) 
}) 

$('#question_vote_down').live('ajax:success', function(evt, data,  status, xhr) { 
$('#question_vote_up').remove() 
$('#question_vote_down').remove() 
alert(xhr.responseText) 
}) 
</script> 

<% if current_user != @question.user %> 
<%= link_to t('question.vote_up'), { :action => "vote_up" }, :id => "question_vote_up", :remote => true %> 
<%= link_to t('question.vote_down'), { :action => "vote_down" }, :id => "question_vote_down", :remote => true %> 
<% end %> 

我無法弄清楚如何不重複自己,如果有一個更清潔的方式到

if current_user != @question.user 

在此先感謝

回答

0

像下面可能工作(沒有測試過,只要確保不增加一倍渲染):

def getQuestion(direction) 
    @question = get_question params[:id] 
    if current_user != @question.user 
     render :json => @question.vote(current_user, direction).to_json 
    else 
     render :nothing => true 
    end 
end 

def vote_up 
    getQuestion "up" 
end 

def vote_down 
    getQuestion "down"  
end 
+0

這是一個很好的方法,但在CURRENT_USER == @question的情況。用戶渲染沒有引發「模板缺失錯誤」。 – invaino 2011-04-15 07:46:26

+0

好吧,你也可以返回一個空對象,只要你能處理這個條件。我已經做了一個編輯來加入。 – mistagrooves 2011-04-18 01:15:50