我花了几天时间(比如4)试图解决这个问题。我遵循了Hartl Rails 3教程,并在第12章中尝试将站点从原型转换为jQuery。但是,我无法通过“跟随”/“取消关注”按钮进行更新。
我能够从Safari的Inspect Element Console中发出jQuery命令,但是如果我将最简单的jQuery命令放入destroy.js.erb或create.js.erb文件中,则没有任何反应。该日志指示正在呈现适当的relations / destry.js.erb(或create.js.erb)文件。
以下是我在控制器中的代码:
class RelationshipsController < ApplicationController
before_filter :authenticate
def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
end
users / _follow.html.haml是
- relationship = current_user.relationships.build(:followed_id => @user.id)
= form_for(relationship, :remote => true) do |f|
= f.hidden_field :followed_id
.actions= f.submit "Follow"
users / _unfollow.html.haml是
- relationship = current_user.relationships.find_by_followed_id(@user)
- delete = { :method => :delete }
= form_for(relationship, :html => delete, :remote => true) do |f|
.actions= f.submit "Unfollow"
users / _follow_form.html.haml是
- unless current_user?(@user)
#follow_form
- if current_user.following?(@user)
= render 'unfollow'
- else
= render 'follow'
relationships / create.js.erb是
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')
relationship / destroy.js.erb是
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')
但是,在尝试诊断时,我尝试了一个非常基本的
$("#title").html("Followed")
这也行不通。
答案 0 :(得分:1)
看起来像是如何使用jQuery的问题。
jQuery使用CSS样式选择器,而Prototype则不使用。因此,要使其工作,只需在选择器中添加“#”符号即可。
而不是
$("follow_form").html("something");
你应该使用
$("#follow_form").html("something");
// Note the # symbol in the selector.
// Also, remember to end your statements with a semicolon.
您可以在此处阅读有关jQuery ID选择器的信息:http://api.jquery.com/id-selector/
答案 1 :(得分:0)
检查您的公用文件夹中是否有Assets文件夹,其中包含application.js.不知道我是如何结束的,但这导致ajax查询被处理两次。
答案 2 :(得分:0)
看起来您可能正在使用Rails 3.1。如果想要相同的结果,使用本教程中使用的确切gem版本(包括Rails 3.0而不是3.1)非常重要。有关更多建议,请参阅Rails Tutorial Help page上的调试提示。