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
在此先感谢
这是一个很好的方法,但在CURRENT_USER == @question的情况。用户渲染没有引发“模板缺失错误”。 – invaino 2011-04-15 07:46:26
好吧,你也可以返回一个空对象,只要你能处理这个条件。我已经做了一个编辑来加入。 – mistagrooves 2011-04-18 01:15:50