Working as Sr. Ruby on Rails engineer at Sedin Technologies, India. You can call me the world's happiest engineer. 😇
You are a developer full of joy and enthusiasm toward changing the world, writing ninja codes driving million-dollar businesses every day. Maybe you have to write code for displaying customer/products/orders data in a table and you spend a month writing pagination, sorting, searching, async fetching and blah-blah. Well, let me help you then by opening the gates to datatables.
Since you already are an awesome developer, I’ll skip the formal introduction, and let’s get started by knowing how our new friend is going to help us:
1. rails new tables -T
skips testing from your application. We won’t need it for our demo app.
2. Add the following gems in your Gemfile:
3. Let's quickly scaffold a model, say, the Customer:
rails g scaffold customer name age city gender
4. Time to scaffold a datatable for our lovely customers:
rails g datatable Customer
Let’s start implementing datatable now. Our target to hook up datatable in UI and exchange data without page refresh.
First, we’ll modify app/views/customers/index.html.erb as:
Well, since this is just a demo, let’s go the dirty way and hook scripts right in our view files. But, beware if you do in your actual application, Hell is a sure thing for you.
What you need to notice here is that we are using a table tag with a data-source attribute assigned to UsersController’s index route. Rest we don't need to provide any data in the table body. After all, if we do everything, what datatable is for.
Now, its time for putting some logic in the datatable file we generated earlier, our app/datatables/customer_datatable.rb will now look like this:
👉 Github codes for this demo: https://github.com/sameer1612/datatable-demo
I am planning to write on Ruby on Rails, every Sunday. 🙌
👉 This article is written considering the reader is fresher to rails, so, reserving in-depth exploration for part 2. Stay Tuned!
If you have any doubts, put them in the comments, I’ll answer asap. Also, if you want to know about some specific topic, do mention it, I’ll definitely write on it soon.
If you want to connect:
👉 Sameer Kumar: https://www.linkedin.com/in/sameerkumar1612/
Also published on Medium subdomain: https://sameer1612.medium.com/datatable-on-rails-e371fe5a747d
Create your free account to unlock your custom reading experience.