Raty.js Star Plugin Rails 6

Nicole Stellatos
3 min readMay 5, 2021

In my app, I thought it would be cool to add the functionality to input stars as a rating rather than a number. When I was researching how to do this, most of the tutorials I came across were outdated and did not work for me. In this tutorial I will be demonstrating how I got the raty.js plugin to work in rails 6.

IMPORTANT: for this to work, you must use the yarn add command line:

yarn add jquery

This will write the version to package.json as well as install the package. Next, you need to go into config/webpack/enviornment.js & describe how to add jQuery

Next Steps: Downloading the star images

Go to https://github.com/wbotelhos/raty and download star-on.png, star-off.png & star-half.png

Add these images under app/assets/images. It should look something like:

Implementing raty.js

Create a file in app/javascript/packs named raty.js

** the source code on the github/raty did not work for me, in order to follow along with this tutorial, go to my github link for this project and copy and paste the code into the file.

https://github.com/Nstellatos/SlimeSocial/blob/main/app/javascript/packs/raty.js

Updating the forms:

Instead of having a text field input for a rating, it is time to implement raty.js and use some stars.

It is important to have the <div id=”rating-form”> in order for the app to recognize the raty implementation.

At the very bottom is where you want to add the <script>. It is important to make sure the score name matches the model and attribute or else it will not work.

Displaying the stars

I chose to have the stars(rating) displayed on my recipe show page.

app/views/recipes/show.html.erb

At the very bottom add the script tag

Update your controller:

Once again, I am displaying my stars on my recipes show page.

app/controllers/recipes_controller.rb — show action

Here I am setting my @average_review instance variable to a value of 0 if there are no reviews. If there is a review or many reviews the @average_review instance variable will be set to whatever the average of the reviews are.

Hope this helps :)

--

--