I cannot get Ajax to work in my Rails application.
With the magic of Ajax: When I click the follow button, it should update the number of followers that the user sees on the profile page, without having to refresh the page. However, this does not happen to me in my sample application.
What happens is that the follow button changes to “unfollow” when clicked, as it should, but the number of followers remains the same until I remove the update button in the web browser (checked in FF and IE ) I follow Michael Hartl railstutorial.org using Rails 4 and Ruby 2.0.0p195.
This is the console message I get from FireFox:
An empty string is passed to getElementById ().
This is my code below, the follow button in the view corresponds to the actions in the relationship controller, and they should remove the partial parts of create.js.erb and destroy.js.erb.
-CONTROLLER -
relationships_controller.rb
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
-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, with the parameters _follow.html.erb and _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 %>
Note. I use postgreSQL for development instead of SQLlite, which is used in the registry.
EDIT's answer: _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>