【发布时间】:2011-08-05 17:10:06
【问题描述】:
我是 Rails 新手,我想知道是否可以重构以下代码。
基本上,我想对 ajax 中的问题进行投票。
控制器:
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
提前致谢
【问题讨论】:
标签: ruby-on-rails ajax ruby-on-rails-3