Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
What is the proper way to call javascript functions from within a rails view?

I'm really new to rails and the asset pipeline has been tripping me up for a bit. From what I understand, all javascript files in the assets/javascripts directory are compiled into one singular js file called application.js that contains all the functions in all the js files in the directory. My first question is, what happens if there's a naming conflict and two files in assets/javascripts have functions with the same name?

Secondly, what's the best practice for calling these functions? For example, in my view, I have a modal with a form that when submitted, I want the modal to disappear. I can do this

app/views/my_directory/index.html.haml

= form_with url: my_directory_path, class: "form", :html => { onsubmit: "hideModal()" },  method: :get do |form|
            = form.date_select
            %br
            %button.btn.btn-primary{type: "submit", class: "submitBtn"} Submit

app/assets/javascripts/modal.js

function hideModal() {
    $modal.modal('hide');
}

And that works fine. But from what I've read, it's not good practice to call javascript from within your rails view. So my second question is, what IS good practice? I've tried to delete the onsubmit option from my form and do this instead

modal.js

$('.form').submit(function() {
$modal.modal('hide');
})

but this doesn't work. I assume because it can't find the form, because there's no script tag with the javascript file within the index.html.haml. My guess is I'm misunderstanding how the asset pipeline works and how it "links" your javascript files and views together.

I'm working with Rails 5.2.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!