Tuesday, 16 January 2024

How to add jquery and bootstrap in rails 7

 1. Add gem: 

gem 'jquery-rails'

gem 'jquery-ui-rails'

gem "bootstrap"

gem "sassc-rails"

Run: bundle install

-----------------------------------------------------------

2. config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( jquery.min.js jquery_ujs.js bootstrap.min.js )

--------------------------------------------------------------------------------------------------------------

3. config/importmap.rb

pin "jquery", to: "jquery.min.js", preload: true
pin "jquery_ujs", to: "jquery_ujs.js", preload: true
pin "bootstrap", to: "bootstrap.min.js", preload: true

---------------------------------------------------------------------------------

4. app/assets/stylesheets/application.scss

@import "bootstrap";

-------------------------------------------------------------------
5. /app/javascript/application.js

import "jquery"
import "jquery_ujs"
import "bootstrap"

Then restart server: rails server


Form tag and auto submit form after 1 sec.

<div class="container-fluid">
  <div class="row mt-4">
    <div class="col-md-6">
    <%= form_tag "/fetch_breed", class: "inline-form", id: "breed_form", remote: true do %>
        <label for="breed">Breed:</label>
        <input type="text" id="bname" name="breed" class="form-control" value="affenpinscher">
        <button type="submit" class="btn btn-success">Submit</button>
      <% end %>
    </div>
    <div class="col-md-6">
      <div class="show_breed"></div>
    </div>
  </div>
</div>

<script type="text/javascript">
setTimeout(() => {
  $("#breed_form").submit();
}, "1000");
</script>


No comments:

Post a Comment