link_to上的ajax请求方法:在禁用javascript的情况下放入rails

时间:2012-11-27 06:57:11

标签: javascript ruby-on-rails ruby-on-rails-3 jquery ruby-on-rails-3.1

我有一个链接,通过方法put发送一个ajax请求。它运行正常,启用了javascript。因此,当我禁用javascript它发送一个get请求。我甚至尝试使用link_to中的方法帖子没有运气。任何帮助不胜感激..

路由

resources :coupon_votes ,:only => [:voted_down,:voted_up] do 
  member do 
    put 'voted_up'
    put 'voted_down'    
  end
end

查看

link_to(image_tag("coupon/works_yes_icon.png",:alt => "Worked",:size =>"16x15"),voted_up_coupon_vote_path(object.id),:html => {:remote => true, :method=>:put},:id => "voted_up_voted_up_#{object.id}",:class => "working")
link_to(image_tag("coupon/works_no_icon.png",:alt => "Did not work",:size => "16x15"),voted_down_coupon_vote_path(object.id),:remote => true, :method=>:put , :id => "voted_up_voted_down_#{object.id}",:class => "not_working"))

控制器

def voted_up
  comman_vote do 
    @coupon.vote_up(current_user)
  end
end

def voted_down
 comman_vote do 
  @coupon.vote_down(current_user)
 end
end



def comman_vote
  if current_user && current_user.active?
    yield       
  end
respond_to do |format|
  format.js {render  "coupon_voted"}
  format.html {render :text => "Thanks for the vote! Please enable javascript to use all the features of the website."}
end
end

def find_coupon
  return if !current_user
  @coupon=Coupon.find(params[:id])
end

更新

谢谢大家的努力。我做了另一种方式,而不是在我使用javascript(application.js)中的link_to中使用远程true。

视图

link_to(image_tag("coupon/works_yes_icon.png",:alt => "Worked",:size => "16x15"), "#", :data => {"source" => object.id },:id => "voted_up_voted_up_#{object.id}",:class => "working")

的application.js

$(".working").click(function (){
var coupon_id = $(this).data('source');
var request = $.ajax({url: '/coupon_votes/' + coupon_id + '/voted_down',
  type: 'POST',
  dataType: 'script'
})
return false; 

});

1 个答案:

答案 0 :(得分:1)

问题不在于方法(put),而是调用本身是远程的。这意味着异步调用并需要javascript。