简体   繁体   中英

Adding AJAX 'add to favorite' to this controller?

This is blowing my mind, and there is so much going on that I just need to ask here for help.

Right now, I have a listing of resources. Inside each resource, it allows someone to 'add it as a favorite' by clicking a link. I have it working with normal redirection, but as for integrating ajax so they can favorite without the page refreshing, I am completely lost...

  1. Right now I have it as a "put" action it seems for CRUD 'update'

FavoritesController (update is the only action in this controller)

  def update

    @favorite = Favorite.find_or_initialize_by_resource_id_and_user_id(params[:id], current_user.id)

    if @favorite.persisted?
      @favorite.destroy
    else
       if @favorite.valid?
          @favorite.save
       end
    end

    redirect_to root_url
  end

My view:

<%= link_to "", favorites_path(:id => resource.id), :class => "star#{star_post?(resource)}", :method => "put" %>

My routes:

  resource :favorites, :only => [:update]

My JS:

  $('.res-list .star').click(function(){
    $.put('/favorites/?id=' + $(this).attr('data-id'));
    return false;
  });

There's a couple of ways to do this. You can use link_to_function through which you can pass a javascript method (you can even pass a custom one if you've defined it in the view or in application.js). In this method, you can set up your AJAX call to hit your update action.

View (using jQuery's put macro):

<%= link_to_function "AJAX Link", "$.put('/favorites/#{resource.id}');" %>

Another way to do this is to give your link an addition HTML selector. Again, you would need to write a bit of js to hit your update action. I tend to like this way because I like to use buttons and what not instead of <a href="#"> tags. (Though honestly I ended up just creating a button_to_function method that calls content_tag(:button) instead of content_tag(:a) )

I would recommend starting off with this Railscast on basic JQuery and Ajax processing. It's a bit dated, but is pretty solid still and will give you the basics to get you started.

http://railscasts.com/episodes/136-jquery

It will give you an idea of how to attach the ajax call to the element on your page, handle request processing and craft a basic javascript view partial that will update the form for the user.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM