【问题标题】:Rails 3 - Ajax and controller refactorRails 3 - Ajax 和控制器重构
【发布时间】: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


    【解决方案1】:

    类似以下的方法可能有效(未经测试,请确保不要重复渲染):

    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
    

    【讨论】:

    • 这是一个不错的方法,但在 current_user == @question.user 渲染的情况下,不会引发“模板丢失错误”。
    • 你也可以返回一个空对象,只要你能处理这种情况。我已经进行了编辑以合并它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多