I have to say now, I have come to the end of my first project of building a blog app with Rails. Whilst there are features that can be added to the site, my enthusiasm in this project is wearing off. Therefore, I intend to hold this project for the time being and move on to my next project idea starting tomorrow.
However, there was one more thing I wanted to implement before moving on to the next project. This feature was sorting the blog post by showing the newly created post on top. After having hacked through the solution, this one seemed pretty straightforward, and one line of changed code did the trick.
def index
@post = Post.all.order('created_at DESC')
end
In the post controllers function index, all I needed was to do was add the order
method. The order method would look at the created_at column at sort order the posts in descending order.
With this done, I did also implement a feature that allows the user to press tab when typing inside the textbox while creating a new or editing a blog post.
I hacked my way through this and used vanilla Javascript for this.
var myInput = document.getElementById("textbox");
if(myInput.addEventListener ) {
myInput.addEventListener('keydown',this.keyHandler,false);
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler);
}
function keyHandler(e) {
var TABKEY = 9;
if(e.keyCode == TABKEY) {
this.value += " ";
if(e.preventDefault) {
e.preventDefault();
}
return false;
}
}
I did for a little while encounter difficulty in getting the javascript included in Rails but was finally able to do it.
I included the main.js
the js file I had created in the app > javascripts
folder, and then on application.js
in the app folder, I added the following lines //= require main
. This I thought would work, but it did not. I got the following error in my browser console.
Uncaught TypeError: Cannot read property 'addEventListener' of null
I had to search for a solution and to be honest I haven't done a lot of javascript, so I could not really follow along. Something, that I did get was that the javascript addEventListener
was running even before there was any text on the body textbox of my blog.
For a solution that is working currently for me, I copy pasted the following code
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
at the end of the application.html.erb
document.
With that, I was able to get the tab working on my textbox. I am yet to understand what my issue with javascript was? Or If I am including the js file correctly to my rails app?
All in all, it has been a great learning experience for me. However, I must move on from this app, and start fresh.
Top comments (0)