0

Rails newbie here. I'm looking to learn a little bit about jQuery so I figured I'd try to switch between my views using AJAX. I'm really looking forward to insights in how to do this!

Right now on my user's dash I have a link to their 'likes' page, it requires a full reload to see the 'show_likes' views, how would I refresh the div id="content" with the new view 'show_likes' ??

Thanks!

views/pages/home.html.erb

  <div id="left">
    <div id="dash-statistics">
       <a href="<%= likes_user_path(@user) %>">
         <div id="likes" class="stat">Likes
           <%= @user.likes.count %>
         </div>
       </a>
    </div>
  </div>

  <div id="right">
    <div id="content">
    </div>
  </div>

UsersController

def home
    @title = "Home"

    if user_signed_in?
      @user = current_user
      @post = current_user.posts.build
      @collections = @user.posts.map(&:collections).flatten.uniq
      @recommended_posts_count = @user.posts.where(:is_recommended => true).count 
      @feed_items = @user.feed.paginate(:per_page => "10", :page => params[:page]) 
   end
  end

  def likes
    @title = "Likes"
    @user = User.find(params[:id])
    @like_stuff = @user.likes.paginate(:page => params[:page])
    render 'show_likes' 
  end
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user1009762
  • 199
  • 3
  • 11

2 Answers2

0

There are a few options.

The UJS way would be to have a link_to with a :remote => true. See this post for some details.

This blog post goes in to more details, but is a bit heavy, and discusses one particular implementation that may or may not be to your liking.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

You should add :remote => true to your link, and then in your views create a likes.js.erb file. Also add

respond to do |format|
  format.js
end

to your controller method. In the js.erb file you can mix javascript and ruby and show/hide/replace divs as you please. You should look at the methods provided by jquery (such as replaceWith) to modify the divs.

Wahaj Ali
  • 4,093
  • 3
  • 23
  • 35