Builder Interview PReparation

  What is Associations ::


 Association defines the relationship between models.Association is a connection between two active record models.It makes easer to perform various operations on the record in your code.




 Why we Use Association ::

 

 Because they make common operations simpler and easier in your code.



 What is Join Method ::

 Join Method is the      


.................................................................................


What is the map method ::


The map() method in Javascript creates an array by calling a specific function on each element present in the parent array.It is non mutating method.Fenerally map method is used to iterate over an array and calling functon on every element of array.



 What is include Method ::


 .................................................................................



 What is Self Join ::


 Self Join is the Join Method in which Table join with itself with the use of Foreign key which reference its own primary key instead of default id , and it makes two copies of the same table.

 .................................................................................



 What is Api ::

 

 Api is the :: Application Programming Interface , it allows to two applications can talk each other.It is a set of code that governs the way software interacts with other software -it is the communication between the software that facilitate interaction.

 .................................................................................



 Why we use Api ::


 through the api we can share the information among different applications or websites where we can share the information in a particular set of code.We can share and update the information,this is the secure sharing of information exchange among difference websites.Some websites can expose some of their data to some websites.        


.................................................................................


What are the different types of Associations and explain each types of the Association.


.................................................................................


What is the difference between Join Method and Inclue Method ?


In the Join method we always call the data and run the queries whenever we want to retrive the data so system is overkill and to escape this problem we use include method which ensures with active record with minimum possible no of queries.



Tell about yourself ?

Sir myself Dwijendra belong from Bulandshahr(U.P.), I qualified B.tech and M.Tech in Electronic and Wireless Comm , I am working with Bittern Technologies from past two years ,I have worked with Ecommerce Project and my current Project is skool management system.


Skool Management System :: This is the application in which the website owner  Superadmin provides subdomain with Admin and password to different school principals or owners ,they can access their individual schools by creating different roles and their passwrods in their schools such as student ,parent,teacher and other roles and they can access their school by their Role credentials ,can access the web page according to their role accessibility.


Ecommerce Application :: This is the application between the customers and suppliers.Each supplier can make account , show their product at the web portal where customer can compare the products according to its features and price,order that and payement.










Ruby on Rails Errors :: Comes at different times :: 10 to 20 Errors ::




What are the Rails Transactons ::


Rails Transactions is a way that ensures that a set of database operations happen only when all database operations succeeded otherwise it rollback to its previous state.


Difference between redirect_to and render ?

we use redirect when the user needs to redirect its response to some other pages or URL and we use render when we want to render the full page.






Association Types all Explained ??


Polymorphic Association ::

Has many through Association ::

Has one through Association ::

Has and belongs to many Association ::

Self Join ::

What is the difference between Hasmany through and Has and blongs to many?



Polymorphic Association ::  One to Many Association

With Polymorphic Association a model can belongs to more than one other model on a single Association.This is one to many Association.


Has many through Association :: Many to Many Association

The has many through Association is when we setup the many to many connection with other model.This association indicate that declaring model can be matched with zero or more instances of another model by proceeding through a third model.



Has one through Association :: One to one Association

This setup a one to one connection with another model.This association indicates that the declaring model is matched with one instance of another model by proceeding through a third model.



Has and belongs to many Association :: Many to Many Association

This association create the direct many to many connection with another model with nointervening model.


 Self Join Association ::


 Self Join is the Join Method in which Table join with itself with the use of Foreign key which reference its own primary key instead of default id , and it makes two copies of the same table.



What is the difference between Hasmany through, Has one through  and Has and blongs to many?



In has one through we connect the one model with the instance of another model with the reference of third model.

In has many through we connect the one model with the instances of another model with the 

reference of third model.

In has one and has many the model has its independent identity.




What is MVC ?



What is Active Record ?

Active Record is M in the MVC,this isresponsible to represent business data and logic.

Active Record is an ORM(Object Relational Mapping) which maps the models to database tables.

This simplify setting up an app because we can not directly write - to save ,load or delete objects.It also provides some protection against SQL Injection.


Rails Active Record is the Object/Relational Mapping(ORM)layer supplied with Rails .It follows the standard ORM Model as

Table map to classes.

Rows map to objects.

Columns map to object attributes.






What is ORM :: Object Relational Mapping :: In this technique we can connect the rich objects of an application to the Table.


Imp :: When we use ORM then we do not use the SQL Statement and we can easily stored and retrive the objects without writing SQL Statement in the database.



What are the Initializers in Rails ??????


Intializers hold the configration logic and only run when an app is booted.This means that Rails Server needs to be restarted if initializers are changed.The exist in the config /initializers directory. 



What is MVC ?

M :: The Model manages the data and logic.

V :: The View displays the information

C :: The Controller takes input and prepares data for a model or view.



Validations ?


Validations are the methods through which we can validate the state of the model before it writes in the database.


Migrations ?


Rails provide the domain specific language for managing database schema , this is called migrations.


Callbacks ? 

With the help of Callbacks , we can write the code in the lifecycle of the model at some particular events, and whenever these events are called then this code is execute .



Most Important ::


First see the query interface then also take a look of validations and callbacks he can also checkyour knowledge by this.


What are the scopes in Rails ?? 


Scopes are the custom queries which you define inside your Rails models with the scope method.Every scope takes two arguments :: A name which  you use to call this scope in your code , A Lambda :: which implements the quey.



What do you mean by map ?? What is the Map method in the JAvascipt ::


The map method in the javascript creates an Array by calling a specific function on each element present in the Parent Array.It is non-mutating method generally map method is used to iterate over an array and calling function on every element of array.



What is Froeign keys and primary Keys ::


Foregin Key :: This is the filed to which Active Record will see when we create Associations between Tables.


Primary Key :: Every table has its key and we say it Primary Key and it is made by default.



What is Coc in Active Record ?????


Active Record :: When we work with the other languages then we write a lot of configration code but when we follow the Rails convention then we write very less code.This is called convention over configration and there are two types of the Coc :: 

Naming Conventions

Schema Conventions.



What is CSRF ??  Cross Site Request Forgery ??


CSRF is a type of attack in which sensitive data is damage or steal  and we write the 'protect_from_forgery' in the application controller  whic generates a CSRF Token and is required to process your request:: to save by the CSRF attack.




What are the Left Outer Joins:: 

When we want to select the :: set of Records ,Whether these are the Associated Records or not then we use the left outer joins method.


What are the types of Routes ??





What are the namespace Routes in Rails ??




Type of HTTP Request Methods ??

............................................



GET ::  Retrive a Resource 

POST :: Create a Resource

PUT :: Completely Update a Resource 

PATCH :: Partially Update a Resource

DELETE :: Delete a Resource





What is the difference bwtween Namespace and Scope Routing ??

https://devblast.com/b/rails-5-routes-scope-vs-namespace


Scope Method Examples in Rails ???? Give a Important Link ??

https://www.rubyguides.com/2019/10/scopes-in-ruby-on-rails/




Give Example of Seven different basic Routing 




get '/hotels', to: 'hotels#index'

get '/hotels/:id', to: 'hotels#show'

get '/hotels/new', to: 'hotels#new'

post '/hotels', to: 'hotels#create'

get '/hotels/:id/edit', to: 'hotels#edit'

put '/hotels/:id', to: 'hotels#update'

delete '/hotels/:id', to: 'hotels#destroy'



Namespace Routing :: Controller Namespace Routing ??


namespace :admin do 

  resources :articles,:comments

end


/admin/articles





Routing Concerns Link ::


https://api.rubyonrails.org/v6.1.4/classes/ActionDispatch/Routing/Mapper/Concerns.html


https://rubyinrails.com/2019/04/23/rails-routes-concerns/



What is Scaffolding and What is the difference between Dynamic and Static Scaffolding



What are the common Errors that comes in Rails Crud and Application Creation ???????



What are the Rails Filters


What are the Rails Transactions tell thoughrouly


What are the Rails Sessions 


What is JSON




How we can use Scopes in Rails :: do it by the Example ::




Run all important important queries


basic queries write

join queries write

write the where queries

write the find and find each queries

write the scopes queries

write the queries of the batches records and find records

write the queries :: 




Rails Features ::::


Link  :::::


https://www.javatpoint.com/ruby-on-rails-features  


Action Cable 

Rails API

Action Mailer

Action View

Rake Command

Ajax Library

Custom Library


Keyword Arguments

Action Pack Asertions

Rake Commands

Render From Anywhere

Module Prepend



................................................


Scopes


Class Fruit < ApplicationRecord

 scope :with_juice, ->{}

end





Run the Where Queries


Run the Find and find by query and find the record in the batches.




Rails 6 Features ?


Action Mailbox

Action Text

Support Multiple databases with Active Record 

Run Test Cases in parallel :: taking advantages of multiple cases

More Heart for Javascript

Zeitwork :: A nw code loader for Ruby



Routes ::

Rails Restful Design

Resourceful Routes

What are the types of Resourceful Routing

Non Resourceful Routes

Nested Routes

Controller Namespace and Routing 

Naming Routes

Redirecting Routes

Routing Concerns

what is the difference between Resourceful an Non Resourceful Routes 


.........................................................

Nested Routes ::

Nested Routes are the Routes where some Resources are the logically children of some other Resources.

........................

resources : hotels do

 resources :rooms

end

........................

/hotel/:id/rooms

/hotel/:id/rooms/:id

/hotel/:id/rooms/new


..........................................................


What are the types of Resourceful Routing ?

Single and Multiple Resources 

Nested Resources


...........................................................


Controller Namespace and Routing ?


Rails allows us to organize group of controllers under a namespace with a keyword "namespace" during routing. Ex :: Grouping Article and Comment Controller under the Admin Controller.



namespace :admin do

 resources: articles,:comments

end


...................................


semicolon ::

namespace se alag hoga hoga    -   namespace :

resource ke sath hoga - resources:


 ...........................................................


 Single and Multiple Resources ?


 resources: hotels

 resources: hotels, :romms


 ............................................................


Types of Routes ::

Resourceful and Non Resourceful Routes

Resourceful Routes :: Single and Multiple Resources  + Nested Resources

Seven different Routes of Resourceful Routes 

Simple Routes/Basic Routes

Controller and Namespace Routing

Naming Routes

Redirecting Routes 

REST

RESTful Design

Routing Concerns

HTTP Verbs :: Done   :: GET POST PUT PATCH DELETE

Root Routes

Member and Collection Routes

NonResourceful Routes

Member and Collection Routes

...............................................................



Naming Routes :: Instead of using Raw Urls only ,Rails allows us to refer Routes by Names.


Ex :: 


get "session/destroy",as :logout            


Redirecting Routes ::



get 'stories'to: redirect('/articles')

get 'stories',to: redirect('/articles',status:302)



This Route is use for the redirecting the Routes to some other Paths,by default we do not use status in this type of routes and it takes status 301 but it is not acceptable for some old browser if sometimes it takes in the old browser if browser not take this in the first time and take it in the second time then it will move permanently to the redirect route so this is important to use the status method in redirecting routes with the status 302  but in status 302 we used,


......................................................

Example of the Routes ::


01 :: Controller Namespace Routes:


    namespace : admin do

     resources: articles, :comments

    end


01 ::  Route with module or Scope in the Controller Namespace Routing ::


   If in the controller namespace and routing we want to use the Route without prefix of namespace :: means it will not show in the routes ::

   

   .........

   If we want  to route  /articles (without prefix admin) then we will use the  scope block:



   scope module: 'admin' do

    resources :articles, :comments

   end


   for a single Route:


   resources :articles,module: 'admin'

   .........


   If you want to route /admin/articles (without the Admin :: module prefix),you can specify the path with a scope block ::


   scope  'admin' do 

    resources :articles, :comments

   end 


   for a single route 


   resources :articles,path: '/admin/articles'






02 :::::  Nested Routing by the shallow Nesting ??


   








03 :: Member and Collection Routes ::


Member Route ::

A Member Route will require an id,because it acts as a member.A collection route does not require an id because it acts as a collection of objects.Preview is the example of a member Route ,because it acts on(and displays) a single object. Search is an example of a collection Route,because it acts on(and displays) a collection of objects.



resource :posts do

    post :archive,on:member

end


path made ::  /posts/:id/archive


IT has created a route that accepts :id parameter and call archive action on post controller.



Collection Route ::


resource :posts do

    post :search , on:collection

end


path made :: /posts/search(.:format)


Multiple member and collection Routes ::


resources posts do 

 member do 

   post :archive

   get :inactive

 end


collection do

   get :search

   post :upload

end


end



Member Routes acts on a member of the resource.Collection routes acts on resources in general





















For multiple resource ::

scope module: 'admin' do 

  resources :articles, :comments

end


for Single Resource ::

resources :articles, module: 'admin'


   .......................................................



02 :: Naming Routes:

  

     get "session/destroy", as:logout

     get 'exit' to: 'sessions#destroy' as: :logout

     get 'login' to: 'sessions:new',as:'login'

     get 'logout' to: 'sessions:destroy',as:'logout'


03 :: Single Resources Routes:


    resources: articles


04 :: Multiple Resources Routes:

  

    resources: articles, :comments


05 :: Nested Resources Routes:


     resources: admin do

       resources: articles, :comments

     end


     resources :magzines do

       resources :ads

     end



06 :: Redirecting Routes::


    get '/stories' to: redirect(/articles)

    get '/stories' to: redirect(/articles,status: 302)



07 :: Simple Routes:




/roll/1

get'roll/:id'=>'roll#branch'

get'roll/:id to: 'roll/branch'

 

...............

get '/hotels', to: 'hotels#index'

get '/hotels/:id', to: 'hotels#show'

get '/hotels/new', to: 'hotels#new'

post '/hotels', to: 'hotels#create'

get '/hotels/:id/edit', to: 'hotels#edit'

put '/hotels/:id', to: 'hotels#update'

delete '/hotels/:id', to: 'hotels#destroy'

................

   get 'roll/list'   

   get 'roll/new'   

   post 'roll/create'   

   patch 'roll/update'   

   get 'roll/list'   

   get 'roll/show'   

   get 'roll/edit'   

   get 'roll/delete'   

   get 'roll/update'   

   get 'roll/show_subjects'   

.................




08 :: Root Routes:



Root Route simply call the homepage, Root Route is the main action controller of your Ruby on Rails Application.


root "application#index"

root to: 'welcome#index'




09 :: Routes with Singular Resources :: Write with the specific controller#action

Sometimes client want this type of route without referencing an id 


get 'profile', to: "users#show"

get 'profile', action:show, controller: 'users'



Command to check the Routes ::


rake routes 

rails routes 

rails routes| grep hotel  :: If we want to check the particular Route then we use it.



......................................

Crud /Verbs and Actions of the Routes ::


Http Verb            Path                    Controller/Action Used For 


GET                 /photos                  photos#index      Retrive a list of all photos 

GET                 /photos/new              photos#new        return html-form for new photo create 

POST                /photos                  photos#create     create a new photo

GET                 /photos/:id              photos#show       display a specific photo

GET                 /photos/:id/:edit        photos#edit       return html-form for editing a new photo

PATCH/PUT           /photos/:id              photos#update     update a specific photo

Delete              /photos/:id              photos#destroy    delete a specific photo




What is Limits of Nesting and Shallow Nesting in Nested Resources ::

Shallow nesting is used to save by the deeply nesting



By Ex ::


  resources :publishers do

   resources :magzines do

     resources :photos

   end 

  end



  How it route ::      /publishers/1/magzines/2/photos/3







What are the Routing Concern ?

Routing Concerns allow you to declare common routes that can be resued inside other resources and routes.



concern :commentable do

 resources :comments

end


or


resources :comments, concerns: :commentable



resources :messages  do

 resources :comments

 end


 resources :articles do

  resources :comments

  end


  resources :articles do

   resources :comments

   resources :taggable,only: :index

   end






What are the Custom Routes in Rails ??????????????





Very Important Link for Rails Routes of all types ::


https://sodocumentation.net/ruby-on-rails/topic/307/routing



...........................


What is Nested routing with the shallow Option ?


resources :articles do

  resources :comments, shallow: true

end


resources :articles, shallow: true do

  resources :comments

  resources :quotes

  resources :drafts

end


............................



What is MVC Architecture ??


Controller ::  Brains

Model :: Data

View ::  GUI


Model :: Stores and manages data

View :: Graphical User Interface

Controller :: Brains of the Application.The Controller takes input and prepares the data for a model or view.





What are the scopes in the Rails ?


Scopes are the custom queries that we define inside Rails models  with the scope method.

Every Scope has two arguments ::

A Name :: Which you use to call this.scope

A Lambda :: Which implement the query







Give the difference between find, find_by and where ?


with find_by, a single record or Nil

with find , A single Record , found by its primary column (usually id),raises an exception if not found

with where , an Active Record :: Relation Object.


We use find_by if we want a single record

We use where if we want multiple records , ex: a list of users.



Given a Book Model ,with title,author and category


Ex:: Given a Book model with title,author and category ::



find out the books which has the category Ruby

Book.where(category:"Ruby")


find out the books which has the category Ruby and particular author ::

Book.where(category:"Ruby",author:"Jesus Castello")




Api Section is very important so he can ask anything from the api section so 

see video

see tutorial 

of this api section


How many types of Finder Methods are used ::

find

find_by

find_each

find(:first)

find(:last)

find(:all)

where


Exx : Task.where(name:"Get Milk",user_id:3).first



Rails Active Record Queries :: Give the Link

https://apidock.com/rails/ActiveRecord/Base/find/class





What is the difference between find_each and all_each?


Link ::::::::::::


https://rubyinrails.com/2017/11/16/use-find-each-instead-of-all-each-in-rails/



find_each Record ::::::::::::::

Find each get the record in the batches.


find_each ,all_each, find_in_batches,in_batches.




What is find_each ::::  

find_each works on model and classes and also on the relations.




Most Important Question :: It can be asked the difference between find_in and find_in_batches ::


What is the difference between find_in and find_in_batches ::


one returns an emulator and one returns and active record relation


Link :: 


https://stackoverflow.com/questions/58485706/active-record-in-batches-vs-find-in-batches




Important Question :: Very Important Question ::::::


How many Types we can use to run the Where Query ::

This is the third chapter in the where condition ::::::::


01 : Pure String Conditions :: These are the basic conditions we used in the Where Conditions Queries ::


Book.where("title='Introduction to Algorithms'")



02 : Array Conditions ::

Book.where("title=?",params[:title])  :: To specify one condition.

To Specify Multiple Conditions.

Book.where("title=? AND out_of_print=?",params[:title,false])


03 : Hash Conditions 

03 :: A :: Equality conditions

  Book.where(out_of_print: true)

  Book.where('out_of_print'=>true)

03 :: B :: Range conditions


03 :: C :: Subset Conditions

  Customer.where(orders_count:[1,3,5])


04 : Not Conditions

  Customer.where.not(orders_count:[1,3,5])


05 : OR Conditions


  Customer.where(last_name:"smith").or(Customer.where(orders_count:[1,3,5]))





query interface questions



Q 01 ::  How to find out the record single ::


find , take ,first ,last ,find_by


Q 02 :: How to find out the record multiple ::


find_each and find_in_batches 


Q 03 :: Give the types of Where Conditions used ::


A ::  Pure String Conditions.........

B ::  Array Conditions.........

C ::  Hash Conditions.........

C.1 : Equality Conditions

C.2 : Range Conditions

C.3 : Subset Conditions

D ::  NOT Conditions.........

E ::  OR Conditions.........


Q 04 :: How many types of ordering is used in the Query Interface


Q 05 :: How to select specific fields in this ::


Q 06 :: What is the Limit and Offset method in the Query Interface and How we use it ?


Q 07 :: What is Group Method used in the query interface method 


Q 08 :: What do you mean by Overriding Conditions in the Query Interface Method in Ruby on Rails 




08 .A Unscope

08 .B Only

08 .C Reselect

08 .D Reorder

08 .E Reverse Order 

08 .F Rewhere



09 :: What do you mean by null Relation in Query Interface



10 :: What are the ReadOnly Objects in Rails Query Interface



11 :: How many types of Locking Active Record Prodvide ?


A. Optmistic Locking

B. Pessimistic Locking


12 :: How many types of Joining Tables are used ?




13 :: What are the Eager Loading and How We use the Eager Loading Associations ::


14 :: What are the Scopes in Query Interface  and how we use the Scopes in Rails ::


A. Passing in Arguments

B. Using Conditionals

C. Applying Default Scope

D. Merging of Scopes

E. Removing all Scoping


15. What are dynamic finders


16. What are Enums


17. What is Method Chaining and how many types of Method Chaining to retrive the data ::

 

 Retriving Filtered Data from multiple Tables 

 Retriving Specific Data from multiple Tables


15 ::  How to Find or build a new Object in Ruby on Rails ?


find_or_create_by

find_or_create_by!

find_or_initialize_by



16. How to find the data by SQL in Rails ?

A. select all

B. pluck

C. ids



17. What do you mean by Existence of Object? How we can check the existence of the Objeect in Rails?


18. What do you mean by Calculations ?


Count

Average

Minimum

Maximum

Sum




17.



.................................................................



What are the Scopes in Rails ?


Scoping allows you to specify commonly used queries which can reference as method calls on the association objects or models.



Query Interface :::Rails 


1. What is Active Record Query Interface

2. Retreiving Objects from the Database

3. Conditions :: pure string conditions,array conditions,hash conditions,or conditions,not conditions

4. Ordering

5. Selecting Specific Fields

6. Limit and Offset

7. Group

8. Having

9. Overriding Conditions

10. Null Relation

11. Read Only Objects

12. Locking Profile for Update

13. Joining Tables

14. Eager Loading Associations

15. Scopes

16. Dynamic Finders

17. Enums

18. Understanding Method Chaining

19. Find or Build a new Object

20. Find by SQL

21. Existence of Objects

22. Calculations.
































query interface questions



Q 01 ::  How to find out the record single ::


find , take ,first ,last ,find_by


Q 02 :: How to find out the record multiple ::


find_each and find_in_batches 


Q 03 :: Give the types of Where Conditions used ::


A ::  Pure String Conditions.........

B ::  Array Conditions.........

C ::  Hash Conditions.........

C.1 : Equality Conditions

C.2 : Range Conditions

C.3 : Subset Conditions

D ::  NOT Conditions.........

E ::  OR Conditions.........


Q 04 :: How many types of ordering is used in the Query Interface


Q 05 :: How to select specific fields in this ::


Q 06 :: What is the Limit and Offset method in the Query Interface and How we use it ?


Q 07 :: What is Group Method used in the query interface method 


Q 08 :: What do you mean by Overriding Conditions in the Query Interface Method in Ruby on Rails 




08 .A Unscope

08 .B Only

08 .C Reselect

08 .D Reorder

08 .E Reverse Order 

08 .F Rewhere



09 :: What do you mean by null Relation in Query Interface



10 :: What are the ReadOnly Objects in Rails Query Interface



11 :: How many types of Locking Active Record Prodvide ?


A. Optmistic Locking

B. Pessimistic Locking


12 :: How many types of Joining Tables are used ?




13 :: What are the Eager Loading and How We use the Eager Loading Associations ::


14 :: What are the Scopes in Query Interface  and how we use the Scopes in Rails ::


A. Passing in Arguments

B. Using Conditionals

C. Applying Default Scope

D. Merging of Scopes

E. Removing all Scoping


15. What are dynamic finders


16. What are Enums


17. What is Method Chaining and how many types of Method Chaining to retrive the data ::

 

 Retriving Filtered Data from multiple Tables 

 Retriving Specific Data from multiple Tables


15 ::  How to Find or build a new Object in Ruby on Rails ?


find_or_create_by

find_or_create_by!

find_or_initialize_by



16. How to find the data by SQL in Rails ?

A. select all

B. pluck

C. ids



17. What do you mean by Existence of Object? How we can check the existence of the Objeect in Rails?


18. What do you mean by Calculations ?


Count

Average

Minimum

Maximum

Sum




17.



.................................................................



What are the Scopes in Rails ?


Scoping allows you to specify commonly used queries which can reference as method calls on the association objects or models.



Query Interface :::Rails 


1. What is Active Record Query Interface

2. Retreiving Objects from the Database

3. Conditions :: pure string conditions,array conditions,hash conditions,or conditions,not conditions

4. Ordering

5. Selecting Specific Fields

6. Limit and Offset

7. Group

8. Having

9. Overriding Conditions

10. Null Relation

11. Read Only Objects

12. Locking Profile for Update

13. Joining Tables

14. Eager Loading Associations

15. Scopes

16. Dynamic Finders

17. Enums

18. Understanding Method Chaining

19. Find or Build a new Object

20. Find by SQL

21. Existence of Objects

22. Calculations.



































1.find_or_create_by


Customer.find_or_create_by!(first_name:'Andy')



2.find_or_create_by!


Customer.create_with(locked:false)









3.find_or_initialize_by




Find Each Method ::::

The Find each method retrive record in Batches and then yields each one of the block,find each works on models classes and also on relations.


..................


Example for find each method


Customer.find_each do |Customer|

  NewsMailer.weekly(Customer).deliver_now

end


Customer.where(weekly_subscriber:true).find_each do(customer)

  NewsMailer.weekly(Customer).deliver_now

end


User.where('last_seen < ?,2.months.ago').find_each do |Customer|

  user.send_reminder!

end


invalid_user = User.find_each.find(&:invalid?)


...................


Options for Find Each Method ::::



Find Each with Batch Size


Customer.find_each(batch_size:5000) do |Customer|

 NewsMailer.weekly(customer).deliver_now

end




Find Each with Start and Finish


Customer.find_each(start:2000,finish:10000) do|Customer|

    NewsMailer.weekly(customer).deliver_now

end


Find Each with Find in Batches ::


Customer.find_in_batches do|Customer|

  export.add_customers(customers)

end




Customer.recently_active.find_in_batches do|Customers|

  export.add_customers(customers)

end



...................



Find In Batches Method


....................



Options for Find In Batches Method 


....................





Q  :: What is the difference between find_each and find_in_batches


Find each is an extention to Active Record based on the way people use find in batches.find each calls find in batches internally.As discussed earlier find in batches done the same thing.

We can find each without worrying about the batch queries.






































Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5