How to add javascript functions in rails - javascript

I am developing my first rails app i have a controller named article that have about 5 action each action with a view page how do i add a JavaScript function for a certain action in the article.coffee file

First thing
Rename your file as action.js.coffee.
Then
Just bind the actions on the elements for your views of action controller.

Well, as detailed on the Rails Guides if you didn't start your projet with the --skip-sprocket option
rails new myapp --skip-sprocket
the asset pipeline should be enable, wich means you should have files looking like this :
Gemfile
...
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
# gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'turbolinks'
...
application.html.erb
...
<title>myapp</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
...
If this samples look like your app then just add you JS in the application.js file like this :
...
//= require turbolinks
//= require_tree .
function greatTutorial() {
alert('Rails Guides are the best');
}
and then you'll be able to call this function in your views like this :
<h1 onclick="greatTutorial()">Hello World</h1>
If you want to write in Vanilla JS (meaning basic JavaScript, no Coffee or any preprocessor) make your js files end with ".js", but if you wish to write in CoffeeScript make them end with ".js.coffee" in order to be preprocessed before rendering. I recommend you to read the Rails Guides about the Asset Pipeline wich is a gold mine to understand how Rails deals with the assets. Hope this will help you getting started.

Related

Application.js is not working as expected in rails 5.2.6 and ruby-2.6.6 with semantic-ui

I am new to ruby on rails. Currently I am using the above specified version of rails and ruby. While following an old ruby on rails course for building a project. I am facing issues with the semantic-ui components. The JavaScript functionality is not working on components with turbolinks. Particularly the flash messages are using "ui message" but it doesn't close on click. Please have a look. I have tried reinstalling semantic-ui and other changes in application.js but still it haven't solved my problem.
1. Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.6.6'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.6', '>= 5.2.6.2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
gem 'semantic-ui-sass'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'mini_racer', platforms: :ruby
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5.2.0'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
gem 'hirb'
gem 'jquery-rails', '~> 4.4'
gem 'jquery-ui-rails'
# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
gem 'solargraph'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an interactive console on exception pages or by calling 'console' anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
group :test do
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
# Easy installation and use of chromedriver to run system tests with Chrome
gem 'chromedriver-helper'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
2.application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>MessageMe</title>
<%= favicon_link_tag 'favicon.ico' %>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= render 'layouts/navbar'%>
<div class="ui container ">
<%= render 'layouts/messages'%>
<%= yield %>
</div>
</body>
</html>
3.application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//= require jquery3
//=require popper
//= require jquery.turbolinks
//= require jquery_ujs
//= require semantic-ui
//= require rails-ujs
//= require dropdown
//= require activestorage
//= require turbolinks
//= require_tree
$(document).addEventListener('turbolinks:load', function () {
$('.ui.dropdown').dropdown();
$('.message .close').on('click', function () {
$(this).close('.message').transition('fade');
});
})
4.application.css.scss
#import 'semantic-ui';
5.login_form.html.erb
This is the form for my login_page where i am receiving these flash messages.
<%= form_for(:session, html: {class: "ui form", role: "form"}, url: login_path) do |f| %>
<div class="field">
<% f.label :username, "Username"%>
<div class="ui left icon input">
<%= f.text_field :username, placeholder: "Username"%>
<i class="user icon"></i>
</div>
</div>
<div class="field">
<%= f.label :password,"Password" %>
<div class="ui left icon input">
<%= f.password_field :password , placeholder:"Password"%>
<i class="lock icon"></i>
</div>
</div>
<%= f.button "Login", class:"ui blue submit button"%>
<%end%>
this is the login page.
Please pardon me if there are many irregularities or i m using irrelevant libs etc.
Your kind help is appreciated.

Rails 5 Bootstrap Javascript Tags Not Working

I'm having strange issues with Bootstrap 4 and the Rails 5 javascript tags. Everything seemed to work fine when I started on this project and I haven't made any changes to any of the js, but suddenly my collapsable navbar dropdowns stopped functioning, and I can see these errors in the console:
GET http://localhost:3000/packs/js/application-48ce69a491950ec17b29.js net::ERR_ABORTED 404 (Not Found)
GET http://localhost:3000/packs/js/application-48ce69a491950ec17b29.js net::ERR_ABORTED 404 (Not Found)
I am using Rails 5.2.4.1 with Ruby 2.6.3 and Bootstrap 4.
In my application.html.erb I have these javascript tags at the end of the body:
<%= javascript_include_tag 'application' %>
<%= javascript_pack_tag 'application' %>
But I think the problem must be contained in the tags or the files, because when I directly add these Bootstrap script tags into the application.html my dropdowns start working again:
<!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
So this is really confusing me and I want to make sure that the include_tag and pack_tag are actually working so that I can use the asset pipeline to keep other js files organised in folders when I need more.
This is my assets/javascripts/application.js:
//= require rails-ujs
//= require_tree .
And my javascript/packs/application.js:
import "bootstrap";
And here is my config/webpack/environment.js
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
// Preventing Babel from transpiling NodeModules packages
environment.loaders.delete('nodeModules');
// Bootstrap 4 has a dependency over jQuery & Popper.js:
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
})
)
module.exports = environment
I'm using a Devise template made by the LeWagon bootcamp and am not yet confident of how everything is interacting. So here is the gemfile it generated for safe measure:
source 'https://rubygems.org'
ruby '2.6.3'
gem 'bootsnap', require: false
gem 'devise'
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'rails', '5.2.4.1'
gem 'redis'
gem 'autoprefixer-rails'
gem 'font-awesome-sass', '~> 5.12.0'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'
group :development do
gem 'web-console', '>= 3.3.0'
end
group :development, :test do
gem 'pry-byebug'
gem 'pry-rails'
gem 'listen', '~> 3.0.5'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
gem 'dotenv-rails'
end
Am I forgetting to include any other files that might be affecting this? Hopefully someone can spot a simple problem in here, but happy to add more info if I've missed something. This is really getting on my goat lol.
Thanks in advance!
It's not good idea to have javascript_include_tag 'application' and javascript_pack_tag 'application' at the same time
If you use webpacker you don't need app/assets/javascripts folder
And you need to change app/javascript/packs/application.js to something like this:
require("#rails/ujs").start();
require("#rails/activestorage").start();
require("channels");
require("jquery");
import "bootstrap";

Rails jquery can not load in any event

I have tried all the solution in stackoverflow but I still have a trouble with jquery load on rails.It works on localhost but not on heroku.
So, here is my application.js file
//= require jquery
//= require bootstrap
//= require jquery_ujs
//= require_tree .
here is application.css file
*= require_tree .
*/
Here is my gem file;
source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'json', '~> 1.8.2'
gem 'bcrypt', '3.1.7'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails', '5.0.1'
gem 'uglifier', '2.5.3'
gem 'coffee-rails', '4.1.0'
gem 'jquery-rails', '4.0.3'
#//= require turbolinks TO ASSETS gem 'turbolinks', '2.3.0'
gem 'jbuilder', '2.2.3'
gem 'sdoc', '0.4.0', group: :doc
gem "mailboxer"
gem "select2-rails"
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'byebug', '3.4.0'
gem 'web-console', '2.0.0.beta3'
gem 'spring', '1.1.3'
end
group :test do
gem 'minitest-reporters', '1.0.5'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
end
and here is my application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />
<%= javascript_include_tag 'application', 'data-turbolinks-track' => false %>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track' => false %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
The funny thing is, console does not give an error about jquery but my slider does not work. And some of the css changes did not reflect to heroku (I did precompile)
Since Heroku pre-compiles by default, I'd say the error is likely that you have a "polluted" precompiled assets (when you have maybe 8-10 application.js variants in public/assets).
I could - of course - be completely wrong and will happily remove this post, but you may wish to try:
$ rake assets:clean
$ git add .
$ git commit -a -m "Assets"
$ git push heroku master
$ heroku rake assets:clean
This seems to be an assets compilation issue. For heroku make sure your production environment is well configured, take a look to your /config/production.rb, and make sure you have these configs:
config.serve_static_files = false
config.assets.compile = false
config.assets.digest = true
After check the above configs then make sure your public/assets folder is not in .gitignore.
Then precompile assets in local for then redeploy to heroku, run the following command:
rake assets:precompile RAILS_ENV=production
this may take some minutes, after the process finishes then you can commit and push to heroku:
git add .
git commit -m "Precompiled assets for heroku"
git push heroku master

How to add Rails-Jquery back to Rails app?

I'm working with ROR 4. I posted this question about how my link_to wouldn't POST correctly using { method: :post }.
I figured out this was because I removed the Rails-Jquery gem when I first set up my app (this is a side project, I hadn't planned on using Javascript/jQuery or so I thought!).
In an effort to get my POST working, I added the gem back to Gemfile. The file now looks like this:
source 'https://rubygems.org'
gem 'aws-sdk'
gem 'faker'
gem 'jquery-rails'
gem 'inline_svg'
gem 'jbuilder', '~> 2.0'
gem 'nokogiri'
gem 'paperclip'
gem 'pg'
gem 'rails', '~> 4.2.0'
gem 'sass-rails'
I did a bundle install.
I added the below code to application.js:
//= require jquery
//= require jquery_ujs
//= require_tree .
What am I missing? jQuery still isn't loading in the Network tab in Chrome.
I'm guessing I must have changed another config setting on setup (5 weeks ago) that I am now forgetting.
UPDATE: I also removed turbolinks during the main setup. Is that needed for jQuery to work?
If you removed javascript during the initial setup, you are probably missing this from the head of your application.html.erb layout.
<%= javascript_include_tag 'application' %>

Rails 4 jQuery, javascript and coffee scripts not working

I am new to rails and web development, although I have almost two decades of C/C++ in control systems and firmware, and quite a lot of shell and perl scripting.
I can't get jquery to work without explicitly including it, even though it is in the application.js manifest, and I can't get any of the individual coffeescripts to work at all.
Ubuntu 14.04LTS, ruby 2.2.1p85, rails 4.2.0
application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
application.html.erb
<%= render "layouts/header" %>
<%= render "layouts/sidenav" %>
<%= yield %>
<%= render "layouts/footer" %>
_header.html.erb
<html>
<head>
<title>My Application Title</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= stylesheet_link_tag 'intranet' %>
<%= stylesheet_link_tag 'form' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
...
Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'
# Use sqlite3 as the database for Active Record
#gem 'sqlite3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Pagination gem
gem 'kaminari'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Boe
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
I have eleven controllers and views out of 27 built, and they all work well except that I hadn't tried any javascript until yesterday. I wasn't getting any of the expected behavior, so in my "people" index view I added:
...
<script>
$(document).ready(function(){
alert("jQuery is running!");
});
</script>
...
To check and see if jQuery was working at all. If I add <%= javascript_include_tag 'jquery.js' %> before the csrf_meta_tag, I get the alert message but coffeescript and the rest still don't work. Without the explicit jquery include, I get nothing.
I've looked at many, many posts on this, but none of them have worked. It appears to me that the manifest in application.js is not being read and/or the modules listed are not included, except that turbolink appears to work properly gauging by the network panel on the browser when moving from page to page. I removed turbolink and it behaves very differently.
I also tried including the jquery-turbolinks gem, although even though I'm pretty sure it's not needed with the jquery-rails gem. But it doesn't work with turbolinks uninstalled, either, so I don't think that is the conflict.
Thanks for looking.
To resolve this issue I created a blank app with just a 'welcome' controller, containing only the jQuery test script, which worked fine.
Working backwards from the differences in the trees from the naked application, I found that another developer had generated an empty coffeescript file:
app/assets/javascript/application.coffee
I removed this file and the application works properly. The stock javascript_include_tag now reads the manifest and includes the various javascript modules, including jQuery, jQuery-ujs and turbolinks.
Rails 4 automatically adds the sass-rails, coffee-rails and uglifier gems to your Gemfile, which are used by Sprockets for asset compression. So there is no need to add the gem explicitly.
You do not need to add jquery with javascript_include_tag, include your application file instead and let the asset pipeline do its thing. Something like: <%= javascript_include_tag "application" %>
Try adding to config/application.rb
config.assets.enabled = true
You may also want:
config.assets.initialize_on_precompile = true
start your application locally. open your application in any browser. Open the source code of the page. Check if the following line exists
<script src="/assets/jquery.js?body=1" data-turbolinks-track="true">
and if you can see content as follows
/*!
* jQuery JavaScript Library v1.11.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
..........
..........
soon ....
then jQuery works on your application

Categories