Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails3-Ajax和控制器重构_Ruby On Rails_Ajax_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails Rails3-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

我是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 %>

提前感谢

类似于以下内容的功能可能会起作用(未经测试,请确保不要双重渲染):


这是一个很好的方法,但是在当前_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