Ruby on Rails Latest MCQs 2022

Ruby on Rails


Q1. When rendering a partial in a view, how would you pass local variables for rendering?
a. <%= render partial: “nav”, selected: “about”}%>
b.<%= render partial: “nav”, local_variables: {selected: “about”} %>
c. <%= render partial: “nav”, locals: {selected: “about”}

Correct answer is :- <%= render partial: “nav”, locals: {selected: “about”}

Q2. Within a Rails controller, which code will prevent the parent controller’s before_action :get_feature from running?
a. skip_before_action :get_feature
b. skip :get_feature, except: []
c. prevent_action :get_feature
d. :redis_cache_store

Correct answer is :- skip_before_action :get_feature

Q3. Which statement correctly describes a difference between the form helper methods form_tag and form_for?
a. The form_tag method is for basic forms, while the form_for method is for multipart forms that include file uploads.
b. The form_tag method is for HTTP requests, while the form_for method is for AJAX requests.
c. The form_tag method typically expects a URL as its first argument, while the form_for method typically expects a model object.
d. The form_tag method is evaluated at runtime, while the form_for method is precompiled and cached.

Correct answer is :- The form_tag method typically expects a URL as its first argument, while the form_for method typically expects a model object.

Q4. What is before_action (formerly known as before_filter)?
a. A trigger that is executed before an alteration of an object’s state
b. A method that is executed before an ActiveRecord model is saved
c. A callback that fires before an event is handled
d. A method in a controller that is executed before the controller action method

Correct answer is :- A method in a controller that is executed before the controller action method

Q5. Which module can you use to encapsulate a cohesive chunk of functionality into a mixin?
a. ActiveSupport::Concern
b. RailsHelper.CommonClass
c. ActiveJob::Mixin
d. ActiveSupport::Module

Correct answer is :- ActiveSupport::Concern

Q6. In Rails, which code would you use to define a route that handles both the PUT and PATCH REST HTTP verbs?
a. put :items, include: patch
b. put ‘items’, to: ‘items#update’
c. match ‘items’, to ‘items#update’, via: [:put, :patch]
d. match :items, using: put && patch

Correct answer is :- match ‘items’, to ‘items#update’, via: [:put, :patch]

Q7. Which choice includes standard REST HTTP verbs?
a. GET, POST, PATCH, DELETE
b. REDIRECT, RENDER, SESSION, COOKIE
c. INDEX, SHOW, NEW, CREATE, EDIT, UPDATE, DESTROY
d. CREATE, READ, UPDATE, DELETE

Correct answer is :- GET, POST, PATCH, DELETE

Q8. Which ActiveRecord query prevents SQL injection?
a. Product.where(“name = #{@keyword}”)
b. Product.where(“name = ” << @keyword}
c. Product.where(“name = ?”, @keyword
d. Product.where(“name = ” + h(@keyword)

Correct answer is :- Product.where(“name = ?”, @keyword

Q9. Given this code, which statement about the database table “documents” could be expected to be true?
class Document < ActiveRecord::Base
belongs_to :documentable, polymorphic: true
end

class Product < ActiveRecord::Base
has_many :documents, as: :documentable
end

class Service < ActiveRecord::Base
has_many :documents, as: :documentable
end
a. It would include a column for :type.
b. It would include columns for :documentable_id and :documentable_type.
c. It would include columns for :documentable and :type.
d. It would include a column for :polymorphic_type.

Correct answer is :- It would include columns for :documentable_id and :documentable_type.

Q10. Are instance variables set within a controller method accessible within a view?
a. Yes, any instance variables that are set in an action method on a controller can be accessed and displayed in a view.
b. Yes, instance variables set within an action method are accessible within a view, but only when render is explicitly called inside the action method.
c. No, instance variables in a controller are private and are not accessible.
d. No, instance variables can never be set in a controller action method.

Correct answer is :- Yes, any instance variables that are set in an action method on a controller can be accessed and displayed in a view.

Q11. When a validation of a field in a Rails model fails, where are the messages for validation errors stored?
a. my_model.errors[:field]
b. my_model.get_errors_for(:field)
c. my_model.field.error
d. my_model.all_errors.select(:field)

Correct answer is :- my_model.errors[:field]

Q12. If a database table of users contains the following rows, and id is the primary key, which statement would return only an object whose last_name is “Cordero”?

idfirst_namelast_name
1AliceAnderson
2BobBuckner
3CarrieCordero
4DevonDupre
5CarrieEastman

a. User.where(first_name: “Carrie”)
b. User.not.where(id: [1, 2, 4, 5])
c. User.find_by(first_name: “Cordero”)
d. User.find(3)

Correct answer is :- User.find(3)

Q13. How would you generate a drop-down menu that allows the user to select from a collection of product names?
a. <%= select_tag(@products) %>
b. <%= collection_select(@products) %>
c. <%= @products.each do |product| %> <% end %>
d. <%= collection_select(:product, :product_id, Product.all, :id, :name) %>

Correct answer is :- <%= collection_select(:product, :product_id, Product.all, :id, :name) %>

Q14. For a Rails validator, how would you define an error message for the model attribute address with the message “This address is invalid”?
a. model.errors = This address is invalid
b. errors(model, :address) << “This address is invalid”
c. display_error_for(model, :address, “This address is invalid”)
d. model.errors[:address] << “This address is invalid”

Correct answer is :- model.errors[:address] << “This address is invalid”

Q15. Given the URL helper product_path(@product), which statement would be expected to be false?
a. If sent using the PATCH HTTP method, the URL could be used to update a product in the database.
b. If sent using the POST HTTP method, the URL would create a new product in the database.
c. If sent using the GET HTTP method, the URL would execute the show action in ProductsController.
d. If sent using the DELETE HTTP method, the URL would call the destroy action by default.

Correct answer is :- If sent using the POST HTTP method, the URL would create a new product in the database.

Q16. Given this code, which choice would be expected to be a true statement if the user requests the index action?
class DocumentsController < ApplicationController
before_action :require_login
def index
@documents = Document.visible.sorted
end
end
a. The user’s documents will be loaded.
b. The index action will run normally because :index is not listed as an argument to before_action.
c. The require_login method will automatically log in the user before running the index action.
d. The index action will not be run if the require_login method calls render or redirect_to.

Correct answer is :- The index action will not be run if the require_login method calls render or redirect_to.

Q17. In Rails, how would you cache a partial template that is rendered?
a. render partial: ‘shared/menu’, cached: true
b. render_with_cache partial: ‘shared/menu’
c. render partial: ‘shared/menu’
d. render partial: ‘shared/menu’, cached_with_variables: {}

Correct answer is :- render partial: ‘shared/menu’, cached: true

Q18. What is the reason for using Concerns in Rails?
a. Concerns allow modularity and code reuse in models, controllers, and other classes.
b. Concerns are used to separate class methods from models.
c. Concerns are used to increase security of Rails applications.
d. Concerns are used to refactor Rails views.

Correct answer is :- Concerns allow modularity and code reuse in models, controllers, and other classes.

Q19. When using an ActiveRecord model, which method will create the model instance in memory and save it to the database?
a. build
b. new
c. create
d. save

Correct answer is :- create

Q20. You are using an existing database that has a table named coffee_orders. What would the ActiveRecord model be named in order to use that table?
a. CoffeeOrders
b. Coffee_Orders
c. Coffee_Order
d. CoffeeOrder

Correct answer is :- CoffeeOrder

Q21. In ActiveRecord, what is the difference between the has_many and has_many :through associations?
a. The has_many: through association is the one-to-many equivalent to the belongs_to one-to-one association.
b. Both associations are identical, and has_many: through is maintained only for legacy purposes.
c. The has_many association is a one-to-many association, while has_many: through is a one-to-one association that matches through a third model.
d. Both are one-to-many associations but with has_many :through, the declaring model can associate through a third model.

Correct answer is :- Both are one-to-many associations but with has_many :through, the declaring model can associate through a third model.

Q22. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?
a. Create an embedded Ruby file (.html.erb) and surround the Ruby code with <% %>.
b. Insert Ruby code inside standard HTML files and surround it with <% %>. The web server will handle the rest.
c. Create an embedded Ruby file (.html.erb) and surround the Ruby code with <%= %>.
d. Put the code in an .rb file and include it in a tag of an HTML file.

Correct answer is :- Create an embedded Ruby file (.html.erb) and surround the Ruby code with <%= %>.

Q23. How would you render a view using a different layout in an ERB HTML view?
a. <% render ‘view_mobile’ %>
b. <% render ‘view’, use_layout: ‘mobile’ %>
c. <% render ‘view’, layout: ‘mobile’ %>
d. <% render_with_layout ‘view’, ‘mobile’ %>

Correct answer is :- <% render ‘view’, layout: ‘mobile’ %>

Q24. Given this controller code, which choice describes the expected behavior if parameters are submitted to the update action that includes values for the product’s name, style, color, and price?
class ProductController < ActionController::Base

def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
redirect_to(product_path(@product))
else
render(‘edit’)
end
end

private

def product_params
params.require(:product).permit(:name, :style, :color)
end
end
a. The product will not be updated and the edit template will be rendered.
b. The product will not be updated and the controller will raise an ActiveModel::ForbiddenAttributes exception.
c. The product will be updated with the values for name, style, and color, but the value for price will be ignored.
d. The product will be updated with the values for name, style, color, and price.

Correct answer is :- The product will not be updated and the controller will raise an ActiveModel::ForbiddenAttributes exception.

Q25. A Rails project has ActiveRecord classes defined for Classroom and Student. If instances of these classes are related so that students are assigned the ID of one particular classroom, which choice shows the correct associations to define?
A.
class Classroom < ActiveRecord::Base
belongs_to :students, class_name: ‘Student’
end

class Student < ActiveRecord::Base
belongs_to :classrooms, class_name: ‘Classroom’
end
B.
class Student < ActiveRecord::Base
has_many :classrooms, dependent: true
end

class Classroom < ActiveRecord::Base
has_many :students, dependent: false
end
C.
class Student < ActiveRecord::Base
has_many :classrooms
end

class Classroom < ActiveRecord::Base
belongs_to :student
end
D.
class Classroom < ActiveRecord::Base
has_many :students
end

class Student < ActiveRecord::Base
belongs_to :classroom
end

Correct answer is :-
class Classroom < ActiveRecord::Base
has_many :students
end

class Student < ActiveRecord::Base
belongs_to :classroom
end

Q26. Where should you put images, JavaScript, and CSS so that they get processed by the asset pipeline?
a. app/static
b. app/images
c. app/assets
d. app/views

Correct answer is :- app/assets

Q27. If the Rails asset pipeline is being used to serve JavaScript files, how would you include a link to one of those JavaScript files in a view?
a.
b. <%= javascript_include_tag ‘main’ %>
c. <%= javascript_tag ‘main’ %>
d.

Correct answer is :- <%= javascript_include_tag ‘main’ %>

Q28. In Rails, what caching stores can be used?
a. MemCacheStore, MongoDBStore, MemoryStore, and FileStore
b. MemoryStore, FileStore, and CacheCacheStore
c. MemoryStore, FileStore, MemCacheStore, RedisCacheStore, and NullStore
d. MemoryStore, FileStore, MySQLStore, and RedisCacheStore

Correct answer is :- MemoryStore, FileStore, MemCacheStore, RedisCacheStore, and NullStore

Q29. What is the correct way to generate a ProductsController with an index action using only the command-line tools bundled with Rails?
a. rails generate controller –options {name: “Products”, actions: “index”}
b. rails generate controller –name Products –action index
c. rails generate controller Products index
d. rails generate ProductsController –actions index

Correct answer is :- rails generate controller Products index

Q30. If a model class is named Product, in which database table will ActiveRecord store and retrieve model instances?
a. product_table
b. all_products
c. products_table
d. products

Correct answer is :- products

Q31. What is a popular alternative template language for generating views in a Rails app that is focused on simple abstracted markup?
a. Mustache
b. Haml
c. Liquid
d. Tilt

Correct answer is :- Haml

Q32. When Ruby methods add an exclamation point at the end of their name (such as sort!), what does it typically indicate?
a. The method executes using “sudo” privileges.
b. Any ending line return will be omitted from the result.
c. The method will ignore exceptions that occur during execution.
d. It is a more powerful or destructive version of the method.

Correct answer is :- It is a more powerful or destructive version of the method.

Q33. What part of the code below causes the method #decrypt_data to be run?
class MyModel < ApplicationRecord
after_find :decrypt_data
end
a. MyModel.first.update(field: ‘example’)
b. MyModel.where(id: 42)
c. MyModel.first.destroy
d. MyModel.new(field: ‘new instance’)

Correct answer is :- MyModel.where(id: 42)

Q34. Which Rails helper would you use in the application view to protect against CSRF (Cross-Site Request Forgery) attacks?
a. csrf_protection
b. csrf_helper
c. csrf_meta_tags
d. csrf

Correct answer is :- csrf_meta_tags

Q35. In the model User you have the code shown below. When saving the model and model.is_admin is set to true, which callback will be called?
before_save :encrypt_data, unless: ->(model) { model.is_admin }
after_save :clear_cache, if: ->(model) { model.is_admin }
before_destroy :notify_admin_users, if: ->(model) { model.is_admin }
a. encrypt_data
b. clear_cache
c. notify_admin_users
d. None of these callbacks will be called when is_admin is true.

Correct answer is :- encrypt_data

Q36. In a Rails controller, what does the code params.permit(:name, :sku) do?
a. It filters out all parameters.
b. It filters out submitted form parameters that are not named :name or :sku to make forms more secure.
c. It raises an error if parameters that are not named :name or :sku are found.
d. It raises an error if the :name and :sku parameters are set to nil.

Correct answer is :- It filters out submitted form parameters that are not named :name or :sku to make forms more secure.

Q37. Review the code below. Which Ruby operator should be used to fill in the blank so that the sort method executes properly?
[5,8,2,6,1,3].sort {|v1,v2| v1 _ v2}
a. =>
b. <==>
c. <=>
d. ||

Correct answer is :- <=>

Q38. You made a spelling mistake while creating a table for bank accounts. Which code would you expect to see in a migration to fix the error?
A.
class IAmADummy < ActiveRecord::Migration
def change
rename_column :accounts, :account_hodler, :account_holder
end
end
B.
class FixSpellling < ActiveRecord::Migration
def change
rename :accounts, :account_hodler, :account_holder
end
end
C.
class CoffeeNeeded < ActiveRecord::Migration
def change
remove_column :accounts, :account_hodler
add_column :accounts, :account_holder
end
end
D.
class OopsIDidItAgain < ActiveRecord::Migration
def rename
:accounts, :account_hodler, :account_holder
end
end

Correct answer is :-
class IAmADummy < ActiveRecord::Migration
def change
rename_column :accounts, :account_hodler, :account_holder
end
end

Q39. Which HTML is closes to what this code would output?
<% check_box(:post, :visible) %>
A.


B.

C.

D.

Correct answer is :-

Q40. There is a bug in this code. The logout message is not appearing on the login template. What is the cause?
class AccessController < ActionController::Base
def destroy
session[:admin_id] = nil
flash[:notice] = “”You have been logged out””
render(‘login’)
end
a. The string assigned to flash[:notice] will not be available until the next browser request.
b. An instance variable should be used for flash[:notice]
c. This is an invalid syntax to use to assign valuse to flash[:notice]
d. The previous value of flash[:notice] will not be cleared automatically

Correct answer is :- The string assigned to flash[:notice] will not be available until the next browser request.

Q41. Which statement about ActiveRecord models is true?
a. Each database column requres adding a matching attr_accessor declaration in the ActiveRecord model.
b. All attributes in an ActiveRecord model are read-only declared as writable using attr_accessible
c. An instance of an ActiveRecord model will have attributes that match the columns in a corresponding database table.
d. ActiveRecord models can have only attributes that have a matching database column

Correct answer is :- An instance of an ActiveRecord model will have attributes that match the columns in a corresponding database table.

Q42. What is the correct way to assign a value to the session?
A.
$_SESSION[‘user_id’] = user.id
B.
@session ||= Session.new << user.id
C.
session_save(:user_id, user.id)
D.
session[:user_id] = user.id

Correct answer is :- session[:user_id] = user.id

Q43. Which choice best describes the expected value of @result?
@result = Article.first.tags.build(name: ‘Urgent’)
a. either true or false
b. an unsaved Tag instance
c. a saved Tag instance
d. an array of Tag instances

Correct answer is :- an unsaved Tag instance

Q44. What is the correct syntax for inserting a dynamic title tag into the header of your page from within an ERB view template?
A.
<% render :head do %>
My page title
<% end %>
B.
<% content_for :head do %>
My page title
<% end %>
C.
<% render “shared/head, locals: {title: “My page title”} %>
D.
<% tield :head do %>
My page title
<% end %>

Correct answer is :- <% render “shared/head, locals: {title: “My page title”} %>

Q45. How would you validate that a project’s name is not blank, is fewer than 50 characters, and is unique?
A.
class Project
validates :name, presence: true, length: { maximum: 50 }, uniqueness: true
end
B.
class Project
validate_attribute :name, [:presence, :uniqueness], :length => 1..50
end
C.
class Project
validate_before_save :name, [:presence, [:length, 50], :uniqueness], :length => 1..50
end
D.
class Project
validates_presense_of :name, :unique => true
validates_length_of :name, :maximum => 50
end

Correct answer is :- class Project
validates :name, presence: true, length: { maximum: 50 }, uniqueness: true
end

Q46. If a product has a user-uploadable photo, which ActiveStorage method should fill in the blank?
class Product << ApplicationRecord
__ :photo
end

a. has_one_attached
b. has_image
c. attached_file
d. acts_as_attachment

Correct answer is :- has_one_attached

Q47. If the only route defined is resources :products, what is an example of a URL that could be generated by this link_to method?
link_to(‘Link’, {controller: ‘products’, action: ‘index’, page: 3})
A.
/products?page=3
B.
/products/index/3
C.
/products/page/3
D.
/products/index/page/3

Correct answer is :- /products?page=3

Q48. Which part of the Rails framework is primarily responsible for making decisions about how to respond to a browser request?
a. view
b. controller
c. ActiveRecord
d. model

Correct answer is :- controller

Q49. If User is an ActiveRecord class, which choice would be expected to return an array?
a. User.where(last_name: ‘Smith’)
b. User.find_or_create(last_name: ‘Smith’)
c. User.find_by_last_name(‘Smith’)
d. User.find(‘Smith’)

Correct answer is :- User.where(last_name: ‘Smith’)

Q50. Which choice is not a valid Rails route?
a. route “products/index”, to: “products/index”, via: :get
b. match “products/index”, to: “products#index”, via: :get
c. root “products/index”
d. get “products/index”

Correct answer is :- route “products/index”, to: “products/index”, via: :get

Q51. Given a table of blog_posts and a related table of comments (comments made on each blog post), which ActiveRecord query will retrieve all blog posts with comments created during @range?
a. BlogPost.joins (:comments).where(comments: {created_at: @range})
b. BlogPost.where([‘comments.created_at’, @range])
c. BlogPost.preload (“comments.created_at”).where(created_at: @range)
d. BlogPost.includes (:comments).where(‘comments.created_at’ => @range)

Correct answer is :- BlogPost.joins (:comments).where(comments: {created_at: @range})

Q52. Given this Category model with an attribute for “name”, what code would fill in the blank so that it sets saved_name to a string that is the category name that existed before the name was changed?
class Category < ActiveRecord::Base
# has a database column for :name
end

category = Category.first
category.name = ‘News’
saved_name = _
a. category.name_was
b. category.saved(:name)
c. category.changes[:name]
d. category.name_changed?

Correct answer is :- category.changes[:name]

Q53. Given two models, what is the issue with the query used to fetch them?
class LineItem < ApplicationRecord
end

class Order < ApplicationRecord
has_many :line_items
end

Order.limit(3).each { |order| puts order.line_items }
a. This query will result in extensive caching, and you will have to then deal with caching issues.
b. This query will result in the N+1 query issue. Three orders will result in four queries.
c. This query will result in the 1 query issue. Three orders will result in one query.
d. There are no issues with this query, and you are correctly limiting the number of Order models that will be loaded.

Correct answer is :- This query will result in the N+1 query issue. Three orders will result in four queries.

Q54. Which choice is an incorrect way to render a partial?
a. <%= render(:partial => ‘shared/product’) %>
b. <%= render(‘shared/product’, :collection => @products) %>
c. <%= render(template: ‘shared/product’, with: @products) %>
d. <%= render(‘shared/product’, locals: { product: @product }) %>

Correct answer is :- <%= render(template: ‘shared/product’, with: @products) %>

Q55. Which code sample will skip running the login_required “before” filter on the get_posts controller action?
a. before_action :login_required, skip: [:get_posts]
b. skip_before_action :login_required, except: [:get_posts]
c. skip_before_action :login_required, only: [:get_posts]
d. skip_action before: :login_required, only: [:get_posts]

Correct answer is :- skip_before_action :login_required, only: [:get_posts]

Q56. Within a Rails model with a cache_key method, which code snippet will expire the cache whenever the model is updated?
A.
after_update_commit do
destroy
end
B.
after_destroy do
Rails.cache.delete(cache_key)
end
C.
after_update_commit do
Rails.cache.delete(cache_key)
end
D.
after_update_commit do
Rails.cache.destroy(cache_key)
end

Correct answer is :- after_update_commit do
Rails.cache.destroy(cache_key)
end

Q57. After this migration has been executed, which statement would be true?
class CreateGalleries < ActiveRecord::Migration
def change
create_table :galleries do |t|
t.string :name, :bg_color
t.integer :position
t.boolean :visible, default: false
t.timestamps
end
end
end
a. The galleries table will have no primary key.
b. The galleries table will include a column named “updated_at”.
c. The galleries table will contain exactly seven columns.
d. The galleries table will have an index on the position column.

Correct answer is :- The galleries table will include a column named “updated_at”.

Q58. Which code would you add to return a 404 to the API caller if the user is not found in the database?
class UsersController < ApplicationController def show @user = User.find(params[:id]) render json: @user, status: :ok, # Missing code end A. rescue => e
logger.info e
end
B.
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response
C.
rescue ActiveRecord::RecordNotFound
render json: { message: ‘User not found’ }, status: :not_found
end
D.
raise ActiveRecord::RecordNotFound
render json: { message: ‘User not found’ }, status: :user_not_found
end

Correct answer is :- rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response

Q59. What decides which controller receives which requests?
a. model
b. view
c. web server
d. router

Correct answer is :- router

Q60. When rendering a partial in a view, how would you pass local variables for rendering?
a. <%= render partial: “nav”, globals: {selected: “about”} %>
b. <%= render partial: “nav”, local_variables: {selected: “about”} %>
c. <%= render partial: “nav”, locals: {selected: “about”} %>
d. <%= render partial: “nav”, selected: “about”} %>

Correct answer is :- <%= render partial: “nav”, local_variables: {selected: “about”} %>

Q61. Given this code, and assuming @user is an instance of User that has an assigned location, which choice would be used to return the user’s city?
class Location < ActiveRecord::Base
# has database columns for :city, :state
has_many :users
end
class User < ActiveRecord::Base
belovngs_to :location

    delegate :city, :state, to: :location, allow_nil: true, prefix: true
end

a. @user.user_city
b. @user.location_city
c. @user.city
d. @user.try(:city)

Correct answer is :- @user.user_city

Q62. Where would this code most likely be found in a Rails project?
scope :active, lambda { where(:active => true) }

a. an Active Record model
b. an ActionView template
c. an ApplicationHelper file
d. an ActionController controller

Correct answer is :- an Active Record model

Click here to read more Technical Q&A

Q63. What is a standard prerequisite for implementing Single Table Inheritance (STI)?
a. The models used for STI must mix in the module ActiveRecord::STI
b. All models used for STI must include “self.abstract_class=true”.
c. All database tables used for STI must be related to each other using a foreign key.
d. The database table used for STI must have a column named “type”.

Correct answer is :- All database tables used for STI must be related to each other using a foreign key.

Q64. A way that views can share reusable code, such as formatting a date, is called a _?
a. helper
b. utility
c. controller
d. formatter

Correct answer is :- helper

Q65. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?
a. Insert Ruby code inside standard HTML files and surround it with <% %>. The web server will handle the rest.
b. Create an embedded Ruby file (.html.erb) and surround the Ruby code with <% %>
c. Put the code in an.rb. file and include it in a tag of an HTML file.
d. Create an embedded Ruby file (.html.erb) and surround the Ruby code with <%= %>.

Correct answer is :- Create an embedded Ruby file (.html.erb) and surround the Ruby code with <%= %>.

Q66.You are working with a large database of portfolios that sometimes have an associated image. Which statement best explains the purpose of includes(:image) in this code?
@portfolios = Portfolio.includes(:image).limit(20)

@portfolios.each do |portfolio|
puts portfolio.image.caption
end
a. It preloads the images files using asset pipeline.
b. It selects only portfolios that have an image attached.
c. It includes the number of associated images when determining how many records to return.
d. It will execute two database queries of 21 database queries.

Correct answer is :- It will execute two database queries of 21 database queries.

Click here to read more blogs

Click here to read more interview latest technologies questions and Answers

About Author


After years of Technical Work, I feel like an expert when it comes to Develop wordpress website. Check out How to Create a Wordpress Website in 5 Mins, and Earn Money Online Follow me on Facebook for all the latest updates.

Leave a Comment