ahnbizcad
ahnbizcad

Reputation: 10797

AJAX on dynamic class value for Rails

Short version:

If I have

.favorite-link
  = link_to some_path, class: (@condition ? "favorited" : "") do 
    .star-image

routes.rb

  resources :hacks do
    post "favorite", on: :member    
  end

hacks_controller.rb

  def favorite
    @favorite = Favorite.find_or_initialize_by(user_id: current_user.id, hack_id: params[:id])
    if @favorite.persisted?
      @favorite.destroy
      respond_to do |format|
        format.js 
      end
    else
      @favorite.save
      respond_to do |format|
        format.js 
      end
    end
  end

favorite.js.coffee

$('.favorite-link a').toggleClass("favorited")

This last bit of code changes EVERY instance. How do I toggle just the one I clicked? Doing `.on 'click', -> $(this).toggleClass("favorited") does weird stuff, like change it only every other time I click it. Plus, the render js is not suited for that way.

Or perhaps a better way to accomplish toggling the class value is: how do I toggle the star using ajax (i.e. make the page evaluate @condition again after clicking the link?)


Irrelevant to the core of the question, but FYI:

SCSS

.favorite-link {
  a.favorited {
    .star-image {
      background-image: url('star-on.png');
  }   
}

.favorite-link {
  a {
    .star-image {
      background-image: url('star-off.png');
    }
  }   
}

Upvotes: 0

Views: 57

Answers (1)

Substantial
Substantial

Reputation: 6682

Use jQuery to add the class as part of your Ajax response handler:

$(".star-image").addClass("favorited");

There is also .toggleClass and .removeClass to fill out your implementation.

Upvotes: 1

Related Questions