Since the handling of JavaScript has changed from Ruby on Rails 6.0 released in August 2019, I would like to introduce "jQuery Raty --A Star Rating Plugin" based on the changes (stumbling points).
--Language (Ruby 2.6.5) --Framework (Rails 6.0.3.3)
First, install jQuery with Yarn.
yarn add jquery
When managing with Webpacker, use the Node.js package.
Next, in the webpacker configuration file, describe how to add jQuery under management.
config/webpack/environment.js
const { environment } = require('@rails/webpacker')
#Postscript
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
jquery: 'jquery/src/jquery',
})
)
#So far
module.exports = environment
Finally, call jQuery.
app/javascript/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery') #Postscript
Save the image and code locally from the site below. https://github.com/wbotelhos/raty --app / assets / images directory - Image: https://github.com/wbotelhos/raty/tree/master/lib/images --Create a new js file with any name under app / javascript (this time "raty.js") - Code: https://github.com/wbotelhos/raty/blob/master/lib/jquery.raty.js
As before, add the newly created js file.
app/javascript/packs/application.js
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require('jquery')
require('raty') #Postscript
At this point, the function settings are complete.
After that, write as follows to any View file you want to implement.
<div class="note note-rating", id="star">
<h3>Comprehensive evaluation</h3>
</div>
<script>
$('#star').raty({
size : 36,
starOff : '<%= asset_path('star-off.png') %>',
starOn : '<%= asset_path('star-on.png') %>',
starHalf : '<%= asset_path('star-half.png') %>',
scoreName : 'note[rating]',
half : true,
});
</script>
The following two articles are detailed for the description of options and display.
It was almost the first time to introduce jQuery in Rails, so even if I found the function I wanted to implement, I could not introduce it. Since Rails6 or later, Webpacker (a tool for managing JavaScript collectively) is installed as standard, so in order to implement it as you want, you have to learn how to implement it and each file that Rails is composed of. I felt it was necessary.
Recommended Posts