It’s been two months since I moved to ruby world and I can say that it was one of the best decisions I have made. Ruby has great community and I have learned a lot from them, so I decided to take my part and share some handy things and advices I learned in Rails:
Migrations with indexes
As you know when generating migrations you can specify which attributes you want to create. You can also specify index to be added on field
rails g migration add_username_to_link username:string:indexReload Rails console
If you have Rails console running and make changes to models or other parts of application you can use
reload!handy function to reload your console
Messy routes
Then you are declaring resource in your route file, it creates seven different routes for you. Most probably you wont need all of them and your rake routes output becomes clattered with unused routes, to solve that you can use only and except options:
resources :articles, only: [:show, :create]
resources :links, except: :destroyMeaningful method names
Give your method names as much meaning as you can, take your time to think about it, names should read like english:
@user.has_notification_for?(link)
@link.created_by?(user)
@user.member_of?(group)Tap
Tap is Object method which passes itself to block and returns same object. Tap is useful for method chaining or if you want to find some object, do some operations on it and then return same object:
def increment_count_for(username)
User.find_by_username(username).tap do |user|
user.story_count.increment(1)
user.save
end
endRender object
You can pass object or array of objects to render function like this:
render @article
render @usersIt will detect object model and search partial _user in views/users folder,
also you can specify partial if you want too using partial option
Conclusion
There are lots of other cool things you can do with Rails, but I wanted to keep this post simple. I will try to contribute and share my knowledge to ruby community as much as I can.