Skip to content

Instantly share code, notes, and snippets.

@anoobbava
Created June 20, 2017 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anoobbava/bf34bb5a9e8d00bcb690af45852c2b7f to your computer and use it in GitHub Desktop.
Save anoobbava/bf34bb5a9e8d00bcb690af45852c2b7f to your computer and use it in GitHub Desktop.
Models Mistakes
Use ? to Check Boolean Values Present:
-------------------
Department.find(5).is_sub_grouping_enabled?
Use of Bullet Gem to find the eager loading is perfect or not.
------------------------
#############
## WRONG ##
#############
@homeworks = lesson.homeworks
- @homeworks.each do |homework|
%p homework.user.email
#############
## RIGHT ##
#############
@homeworks = lesson.homeworks.includes(:user)
- @homeworks.each do |homework|
%p homework.user.email
Use Scope when ever you can.
------------------------------
############
## WRONG ##
############
def index
@lessons = Сourse.lessons.order(position: :asc)
end
############
## RIGHT ##
############
class Lesson < ActiveRecord::Base
belongs_to :course
scope :by_position, -> { order(position: :asc) }
end
def index
@lessons = course.lessons.by_position
end
After Create and After Commit:
-------------------------
The model’s data including its new ID in “after_create” is available from the inside but not from the outside because the transaction isn’t completed.
Here is what would happen if, say, I created a record in the database and after that I decided to put its ID into redis or any other storage:
“after_create” might result in invalid data if the ID is used before the transaction is completed.
Using “Sidekiq” or any other background worker I could always use “after_commit” to ensure the integrity of my data.
Perfect Use of ORM:
---------
#############
## WRONG ##
#############
Article.all.each { |article| article.delete }
Article.all.map { |article| article.title }
Course.all.select { |course| course.created_at < 5.years.ago }.each { |course| course.articles.delete_all }
#############
## RIGHT ##
#############
Article.delete_all
Article.pluck(:title)
old_courses_ids = Course.where(‘created_at < ?’, 5.years.ago’).pluck(:id)
Article.where(course_id: old_courses_ids).delete_all
Use Depandent_destroy ,when the parent data destroyed.
----------------------
Bang Operator:
------------------
Article.create!(article_data)
and
Article.create(article_data)
bang will return the errors.
Default Value:
---------
1. set default value for the migration.
2.always remember about the size of the coulmns.
Set contstraints in Migration:
------------
class MyMigration
def change
add_column :profiles, user_id, :integer, null: false
end
end
1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment