我无法在我的 Rails 应用程序中使用 Ajax。
借助 Ajax 的魔力:当我单击“关注”按钮时,它应该更新用户在个人资料页面中看到的关注者数量,而无需刷新页面。但是,在我的示例应用程序中,这并没有发生。
发生的事情是,单击“关注”按钮时,它应该更改为“取消关注”但是,关注者的数量保持不变,直到我点击网络浏览器中的刷新按钮(在 FF 和IE)。我正在关注 Michael Hartl 的 railstutorial.org,使用 Rails 4 和 Ruby 2.0.0p195。
这是我从 FireFox 获得的控制台消息:
传递给 getElementById() 的空字符串。
这是我下面的代码, View 中的“关注”按钮对应于关系 Controller 中的操作,它们应该点击 create.js.erb 和 destroy.js.erb 部分。
- Controller - relationships_controller.rb
def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
# redirect_to @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)
# redirect_to @user
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
-JavaScript- _create.js.erb:
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");
$("#followers").html('<%= @user.followers.count %>');
_destroy.js.erb:
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>");
$("#followers").html('<%= @user.followers.count %>');
-VIEWS-是follow_form,带有_follow.html.erb和_unfollow.html.erb。
_follow_form.html.erb
<% unless current_user?(@user) %>
<div id="follow_form">
<% if current_user.following?(@user) %>
<%= render 'unfollow' %>
<% else %>
<%= render 'follow' %>
<% end %>
</div>
<% end %>
_follow.html.erb:
<%= form_for(current_user.relationships.build(followed_id: @user.id), remote: true) do |f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
_unfollow.html.erb
<%= form_for(current_user.relationships.find_by(followed_id: @user), html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>
注意 - 我在开发中使用的是 postgreSQL 而不是 railstutorial 中使用的 SQLlite。
编辑回应: _stats.html.erb
<% @user = @user || current_user %>
<div class="stats">
<a href="<%= following_user_path(@user) %>">
<strong id="following" class="stat">
<%= @user.followed_users.count %>
</strong>
following
</a>
<a href="<%= followers_user_path(@user) %>">
<strong id="following" class="stat">
<%= @user.followers.count %>
</strong>
followers
</a>
</div>
最佳答案
因为在您的 _stats.html.erb 文件中,您没有 ID 为 followers
的元素。请查看您的代码
<a href="<%= followers_user_path(@user) %>">
<strong id="following" class="stat">
<%= @user.followers.count %>
</strong>
followers
</a>
应该是
<a href="<%= followers_user_path(@user) %>">
<strong id="followers" class="stat">
<%= @user.followers.count %>
</strong>
followers
</a>
关于ruby-on-rails - 无法让 Ajax 处理关注/取消关注按钮 - 遵循 Railstutorial.org,第 11 课,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20770509/