0

I have spent a couple of days (like 4) trying to solve this issue. I followed the Hartl Rails 3 tutorial and in chapter 12 tried to convert the site from prototype to jQuery. I am not able to get the "follow"/"unfollow" button to update however.

I am able to issue jQuery commands from within Safari's Inspect Element Console, but if I put even the simplest jQuery command into the destroy.js.erb or create.js.erb files, nothing happens. The log is indicating that the appropriate relationships/destry.js.erb (or create.js.erb) file is rendering.

Here is the code that I have in the controller:

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

The users/_follow.html.haml is

- 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"

The users/_unfollow.html.haml is

- 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"

The users/_follow_form.html.haml is

- unless current_user?(@user)
  #follow_form
    - if current_user.following?(@user)
    = render 'unfollow'
    - else
    = render 'follow'

The relationships/create.js.erb is

$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')

The relationships/destroy.js.erb is

$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
$("#followers").html('<%= "#{@user.followers.count} followers" %>')

However, in trying to diagnose this, I tried a very basic

$("#title").html("Followed")

which also does not work.

4

3 回答 3

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/

于 2011-06-01T19:25:05.030 回答
0

检查您的公用文件夹中的 Assets 文件夹,其中包含 application.js。不知道我是如何结束的,但这导致 ajax 查询被处理两次。

于 2011-12-18T03:03:31.723 回答
0

看起来您可能正在使用 Rails 3.1。如果想要相同的结果,请务必使用教程中使用的确切 gem 版本(包括 Rails 3.0 而不是 3.1)。有关更多建议,请参阅Rails 教程帮助页面中的调试提示。

于 2011-12-18T20:23:07.397 回答