Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails

The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead of just using plain text like/dislike. Can anyone provide some references or guidance?

Below is the code snippet I am currently using for the iconic text implementation:

View code:

if current_user.liked? content
    link_to fa_icon("some-symbol"), dislike_movie_path(content), 
                            class: 'vote', 
                            method: :put, 
                            remote: true, 
                            data: { toggle_text: 'another-symbol', 
                                    toggle_href: like_movie_path(content), 
                                    id: content.id }
  else
    link_to fa_icon("another-symbol"), like_movie_path(content), 
                            class: 'vote', 
                            method: :put, 
                            remote: true, 
                            data: { toggle_text: 'some-symbol', 
                                    toggle_href: dislike_movie_path(content), 
                                    id: content.id }
  end

Javascript code:

$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
  $(".votes-count[data-id=#{data.id}]").text data.count

  $("a.vote[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.text()
    $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    $i = $a.get("i")
    if($i.hasClass('some-symbol'))
      $i.removeClass('some-symbol').addClass('another-symbol')
    else
      $i.removeClass('another-symbol').addClass('some-symbol')
    return
  return

Appreciate any help or insights you may have on this matter.

Answer №1

Here is my proposed solution:

--

Arrangement

#config/routes.rb
resources :videos do
   put :like #-> domain.com/videos/:video_id/like
end

#app/controllers/videos_controller.rb
class VideosController < ApplicationController
   respond_to :js, :json, :html

   def like
      @video = Video.find params[:video_id]

      like = current_user.likes.find _or_create_by video_id: params[:video_id]
      like.toggle(:like)

      respond_with like
   end
end

--

Feature

This setup will enable you to utilize the following functionality:

#app/views/videos/show.html.haml
= link_to fa_icon("some-symbol"), video_like_path(content), class: 'like',  method: :put, remote: true, data: { id: content.id }

In my perspective, it would be beneficial to incorporate the desired styling in the CSS file, allowing you to concentrate on modifying that aspect. The link itself can remain unchanged - offering you the flexibility to determine the vote based on the value it returns:

#app/assets/javascripts/application.js.coffee
$(document).on 'ajax:success', 'a.like', (status, data ,xhr)->
  $(".likes-count[data-id=#{data.video_id}]").text data.count

  $("a.like[data-id=#{data.video_id}]").each ->
     if data.video_id is "1"
        $(this).addClass "thumbs-up"
     else
        $(this).addClass "thumbs-down"
  return

#app/assets/stylesheets/application.css.sass
.like
   & .thumbs-up
     #style for thumbs upvote

   & .thumbs-down
     #style for thumbs downvote

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue Component Unit Testing: Resolving "Unexpected Identifier" Error in Jest Setup

Having just started using Jest, I wanted to run a simple unit test to make sure everything was set up correctly. However, I encountered numerous errors during compilation while troubleshooting the issues. When running the test suite, Jest successfully loc ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

Can a file be successfully retrieved using an HTTP POST request?

Can a file be downloaded using HTTP POST method? I am aware of the "Get" method (windows.location), but in my scenario, there are many parameters that need to be sent to the server. ...

The value of element.scrollTop is consistently zero

Why does the scrollTop position of an element always return 0? How can I correct this issue? JSFiddle var inner = document.getElementById('inner'); window.addEventListener('scroll', function() { console.log(inner.scrollTop); }) # ...

Trouble with recognizing nested functions when calling them in an onClick event

Encountering a `not defined` error on the console when attempting to call nested functions with an `onClick` event in an HTML page. After searching for solutions without success, I suspect it may be a scope or closure issue, but I am unsure of how to addre ...

Leveraging batchWriteItem with dynamodb

I am trying to utilize batchWriteItem in my DynamoDB to add data to two tables: candidate table and user table. The formatted query is shown below: var user = { userid: usrid, role: 'candidate', password: vucrypt.encryptp ...

How can I fetch data from SQL using JavaScript based on a specific value in PHP?

My application is built using the Yii2 framework. Within my application, there is a view.php file that consists of an element and a button. The element, <div id="userId">, contains the user's login ID, and I aim to use the button to re ...

What is the best way to ensure a DOM element exists before you can start manipulating it?

In my AngularJS application, I am utilizing Angular Material and md-select. When a user clicks on the md-select, a dropdown list appears and an overlay with the tag Name is added to the DOM. My goal is to add a class or style as soon as the user clicks on ...

Tips for organizing an AngularJS bootstrap Modal for a search feature

I need help with integrating AngularJs, bootstrap, and an API to populate a bootstrap modal popover with JSON data upon clicking a search function button. While I have successfully implemented the data flow, I am struggling to trigger the modal using the b ...

I am experiencing issues with Kaminari Ajax on my Rails 3.1 application with Mongoid

I am currently following the updates on https://github.com/amatsuda/kaminari_example/commits/ajax. I am using kaminari 0.12.4 (I tested with 0.13.0 and it did not work). The pagination works fine without ajax. In my users_helper.rb module UsersHelper ...

Assign a Value to a Hidden Input Type When a User Submits a Form

I have a straightforward form set up in the following code. I am looking to add the value entered in the rm_accounts text box to the hidden page_confirm input value at the end of the URL. I hope that explanation is clear. In simple terms, if the user type ...

Choose class based on the retrieved information

Good morning, I am working on dynamically setting the class of a td element based on data fetched from a database to reflect any changes or updates. One of the fields returned has four possible options, and I need to modify the CSS class of that field acc ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Retrieving JSON data value without a key using AngularJS

I am struggling to retrieve a data value from a JSON array in Angular that does not have a key value. While I have come across examples of extracting values with keys, I haven't been able to crack this particular piece. The JSON returned from the API ...

An issue with AJAX file upload encountered in JSF/PrimeFaces: Unable to interpret property 'debug' as it is undefined

When I try to submit the save button after uploading a file using the uploadForm, I encounter an error in the console. The errors include: Uncaught TypeError: Cannot read property 'length' of null jsf.js:578 Synchronous XMLHttpRequest on the ma ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

Exploring the Functionality of worker-loader Inline

It was my understanding that the Webpack worker-loader configuration below: ... module: { rules: [ { test: /worker\.js/, loader: "worker-loader", options: { inline: 'fallba ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...