Rails 3: jquery to modify partial data

rails newbie herem, I want to learn a little about jquery, so I decided that I would try to switch between my partial views using AJAX.

Right now, on my user dash, I have a link to their β€œloves” page, it requires a complete reboot to see the β€œloves” page, how can I change it to refresh using lik_user_path @)?

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 likes @title = "Likes" @user = User.find(params[:id]) @like_stuff = @user.likes.paginate(:page => params[:page]) render 'show_likes' end 
+2
source share
1 answer

I understand that you want to restart likes by clicking the link using ajax in the user control panel.

The first thing to do is rewrite the link and add :remote => true as follows:

 <%= link_to "Likes", likes_user_path(@user), :remote => true %> 

Then in your controller, make sure you have respond_to :html, :js at the top (of course, there may be other options, but :js should be among them)

After that, you can execute a function called likes in your controller, which will be used to load your favorites, which looks like yours, only you don’t render at the end, but respond_with @likes . With :js in the respond_to filter, Rails will automatically act accordingly if it is supposed to.

Then make an appropriate presentation called likes.js.erb (I'm not quite sure that coffeescript will work out of the box in this case) into which you put something like

 $('#likes').html('<%= escape_javascript(render "likes", :likes => @likes) %>'); 

This assumes that in the main view in which you want to display similar ones, there is an element with id=likes , which might look like this:

 <div id="likes"> <%= render "likes", :likes => @likes %> </div> 

as well as the _likes.html.erb part that does similar

 <% likes.each do |like| %> <div> <%= like.name %> </div> <% end %> 

And with that, I think I pretty much covered it.

+8
source

Source: https://habr.com/ru/post/910918/


All Articles