Ruby on rails Rails3-Ajax和控制器重构
我是Rails新手,我想知道是否可以重构以下代码 基本上,我想对ajax中的一个问题投反对票,投赞成票 控制器:Ruby on rails Rails3-Ajax和控制器重构,ruby-on-rails,ajax,ruby-on-rails-3,Ruby On Rails,Ajax,Ruby On Rails 3,我是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_questi
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 %>
提前感谢类似于以下内容的功能可能会起作用(未经测试,请确保不要双重渲染):
这是一个很好的方法,但是在当前_user==@question.user render nothing的情况下会引发“模板丢失错误”。您也可以返回一个空对象,只要您能够处理该条件。我做了一个编辑来合并这个。
if current_user != @question.user
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