R4RIN
Articles
Java 8
MCQS
Ruby on Rails MCQ Quiz Hub
Ruby on Rails MCQ
Choose a topic to test your knowledge and improve your Ruby on Rails skills
1. When rendering a partial in a view, how would you pass local variables for rendering?
<%= render partial: “nav”, selected: “about”}%>
<%= render partial: “nav”, local_variables: {selected: “about”} %>
<%= render partial: “nav”, locals: {selected: “about”}
None of the above
2. Within a Rails controller, which code will prevent the parent controller’s before_action :get_feature from running?
skip_before_action :get_feature
skip :get_feature, except: []
prevent_action :get_feature
redis_cache_store
3. Which statement correctly describes a difference between the form helper methods form_tag and form_for?
The form_tag method is for basic forms, while the form_for method is for multipart forms that include file uploads.
The form_tag method is for HTTP requests, while the form_for method is for AJAX requests.
The form_tag method typically expects a URL as its first argument, while the form_for method typically expects a model object.
The form_tag method is evaluated at runtime, while the form_for method is precompiled and cached.
4. What is before_action (formerly known as before_filter)?
A trigger that is executed before an alteration of an object’s state
A method that is executed before an ActiveRecord model is saved
A callback that fires before an event is handled
A method in a controller that is executed before the controller action method
5. Which module can you use to encapsulate a cohesive chunk of functionality into a mixin?
ActiveSupport::Concern
RailsHelper.CommonClass
ActiveJob::Mixin
ActiveSupport::Module
6. In Rails, which code would you use to define a route that handles both the PUT and PATCH REST HTTP verbs?
put :items, include: patch
put ‘items’, to: ‘items#update’
match ‘items’, to ‘items#update’, via: [:put, :patch]
match :items, using: put && patch
7. Which choice includes standard REST HTTP verbs?
GET, POST, PATCH, DELETE
REDIRECT, RENDER, SESSION, COOKIE
INDEX, SHOW, NEW, CREATE, EDIT, UPDATE, DESTROY
. CREATE, READ, UPDATE, DELETE
8. Which ActiveRecord query prevents SQL injection?
Product.where(“name = #{@keyword}”)
Product.where(“name = ” << @keyword}
Product.where(“name = ?”, @keyword
Product.where(“name = ” + h(@keyword)
9. 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
It would include a column for :type.
It would include columns for :documentable_id and :documentable_type.
It would include columns for :documentable and :type
It would include a column for :polymorphic_type.
10. Are instance variables set within a controller method accessible within a view?
Yes, any instance variables that are set in an action method on a controller can be accessed and displayed in a view.
Yes, instance variables set within an action method are accessible within a view, but only when render is explicitly called inside the action method.
No, instance variables in a controller are private and are not accessible.
No, instance variables can never be set in a controller action method.
11. When a validation of a field in a Rails model fails, where are the messages for validation errors stored?
my_model.errors[:field]
my_model.get_errors_for(:field)
my_model.field.error
my_model.all_errors.select(:field)
12. How would you generate a drop-down menu that allows the user to select from a collection of product names?
&lt;%= select_tag(@products) %&gt;
&lt;%= collection_select(@products) %&gt;
&lt;%= @products.each do |product| %&gt; &lt;% end %&gt;
&lt;%= collection_select(:product, :product_id, Product.all, :id, :name) %&gt;
13. For a Rails validator, how would you define an error message for the model attribute address with the message “This address is invalid”?
model.errors = This address is invalid
errors(model, :address) &lt;&lt; “This address is invalid”
display_error_for(model, :address, “This address is invalid”)
model.errors[:address] &lt;&lt; “This address is invalid”
14. Given the URL helper product_path(@product), which statement would be expected to be false?
If sent using the PATCH HTTP method, the URL could be used to update a product in the database.
If sent using the POST HTTP method, the URL would create a new product in the database.
If sent using the GET HTTP method, the URL would execute the show action in ProductsController.
If sent using the DELETE HTTP method, the URL would call the destroy action by default.
15. 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
The user’s documents will be loaded.
The index action will run normally because :index is not listed as an argument to before_action.
The require_login method will automatically log in the user before running the index action.
The index action will not be run if the require_login method calls render or redirect_to.
16. In Rails, how would you cache a partial template that is rendered?
render partial: ‘shared/menu’, cached: true
render_with_cache partial: ‘shared/menu’
render partial: ‘shared/menu’
render partial: ‘shared/menu’, cached_with_variables: {}
17. What is the reason for using Concerns in Rails?
Concerns allow modularity and code reuse in models, controllers, and other classes.
Concerns are used to separate class methods from models.
Concerns are used to increase security of Rails applications
Concerns are used to refactor Rails views.
18. When using an ActiveRecord model, which method will create the model instance in memory and save it to the database?
build
new
create
save
19. 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?
CoffeeOrders
Coffee_Orders
Coffee_Orde
CoffeeOrder
20. In ActiveRecord, what is the difference between the has_many and has_many :through associations?
The has_many: through association is the one-to-many equivalent to the belongs_to one-to-one association.
Both associations are identical, and has_many: through is maintained only for legacy purposes.
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.
Both are one-to-many associations but with has_many :through, the declaring model can associate through a third model.
21. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?
Create an embedded Ruby file (.html.erb) and surround the Ruby code with &lt;% %&gt;.
Insert Ruby code inside standard HTML files and surround it with &lt;% %&gt;. The web server will handle the rest.
Create an embedded Ruby file (.html.erb) and surround the Ruby code with &lt;%= %&gt;.
Put the code in an .rb file and include it in a tag of an HTML file.
22. How would you render a view using a different layout in an ERB HTML view?
&lt;% render ‘view_mobile’ %&gt;
&lt;% render ‘view’, use_layout: ‘mobile’ %&gt;
&lt;% render ‘view’, layout: ‘mobile’ %&gt;
&lt;% render_with_layout ‘view’, ‘mobile’ %&gt;
23. Where should you put images, JavaScript, and CSS so that they get processed by the asset pipeline?
app/static
app/images
app/assets
app/views
24. In Rails, what caching stores can be used?
MemCacheStore, MongoDBStore, MemoryStore, and FileStore
MemoryStore, FileStore, and CacheCacheStore
MemoryStore, FileStore, MemCacheStore, RedisCacheStore, and NullStore
MemoryStore, FileStore, MySQLStore, and RedisCacheStore
25. What is the correct way to generate a ProductsController with an index action using only the command-line tools bundled with Rails?
rails generate controller –options {name: “Products”, actions: “index”}
rails generate controller –name Products –action index
rails generate controller Products index
rails generate ProductsController –actions index
26. If a model class is named Product, in which database table will ActiveRecord store and retrieve model instances?
product_table
all_products
products_table
products
27. What is a popular alternative template language for generating views in a Rails app that is focused on simple abstracted markup?
Mustache
Haml
Liquid
Tilt
28. When Ruby methods add an exclamation point at the end of their name (such as sort!), what does it typically indicate?
The method executes using “sudo” privileges.
Any ending line return will be omitted from the result.
The method will ignore exceptions that occur during execution.
It is a more powerful or destructive version of the method.
29. What part of the code below causes the method #decrypt_data to be run? class MyModel < ApplicationRecord after_find :decrypt_data end
MyModel.first.update(field: ‘example’)
MyModel.where(id: 42)
MyModel.first.destroy
MyModel.new(field: ‘new instance’)
30. Which Rails helper would you use in the application view to protect against CSRF (Cross-Site Request Forgery) attacks?
csrf_protection
csrf_helper
csrf_meta_tags
csrf
31. 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 }
encrypt_data
clear_cache
notify_admin_users
None of these callbacks will be called when is_admin is true.
32. In a Rails controller, what does the code params.permit(:name, :sku) do?
It filters out all parameters.
It filters out submitted form parameters that are not named :name or :sku to make forms more secure.
It raises an error if parameters that are not named :name or :sku are found.
It raises an error if the :name and :sku parameters are set to nil.
33. 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}
=&gt;
&lt;==&gt;
&lt;=&gt;
||
34. 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
The string assigned to flash[:notice] will not be available until the next browser request.
An instance variable should be used for flash[:notice]
This is an invalid syntax to use to assign valuse to flash[:notice]
The previous value of flash[:notice] will not be cleared automatically
35. Which statement about ActiveRecord models is true?
Each database column requres adding a matching attr_accessor declaration in the ActiveRecord model.
All attributes in an ActiveRecord model are read-only declared as writable using attr_accessible
An instance of an ActiveRecord model will have attributes that match the columns in a corresponding database table.
ActiveRecord models can have only attributes that have a matching database column
36. Which choice best describes the expected value of @result? @result = Article.first.tags.build(name: ‘Urgent’)
either true or false
an unsaved Tag instance
a saved Tag instance
an array of Tag instances
37. If a product has a user-uploadable photo, which ActiveStorage method should fill in the blank? class Product << ApplicationRecord __ :photo end
has_one_attached
has_image
attached_file
acts_as_attachment
38. 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})
/products?page=3
/products/index/3
/products/page/3
/products/index/page/3
39. Which part of the Rails framework is primarily responsible for making decisions about how to respond to a browser request?
view
controller
ActiveRecord
model
40. If User is an ActiveRecord class, which choice would be expected to return an array?
User.where(last_name: ‘Smith’)
User.find_or_create(last_name: ‘Smith’)
User.find_by_last_name(‘Smith’)
User.find(‘Smith’)
41. What decides which controller receives which requests?
model
view
web server
router
42. When rendering a partial in a view, how would you pass local variables for rendering?
&lt;%= render partial: “nav”, globals: {selected: “about”} %&gt;
&lt;%= render partial: “nav”, local_variables: {selected: “about”} %&gt;
&lt;%= render partial: “nav”, locals: {selected: “about”} %&gt;
&lt;%= render partial: “nav”, selected: “about”} %&gt;
43. 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
@user.user_city
@user.location_city
@user.city
@user.try(:city)
44. Where would this code most likely be found in a Rails project? scope :active, lambda { where(:active => true) }
an Active Record model
an ActionView template
an ApplicationHelper file
an ActionController controller
45. What is a standard prerequisite for implementing Single Table Inheritance (STI)?
The models used for STI must mix in the module ActiveRecord::STI
All models used for STI must include “self.abstract_class=true”.
All database tables used for STI must be related to each other using a foreign key.
The database table used for STI must have a column named “type”.
46. A way that views can share reusable code, such as formatting a date, is called a _?
helper
utility
controller
formatter
47. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?
Insert Ruby code inside standard HTML files and surround it with &lt;% %&gt;. The web server will handle the rest.
Create an embedded Ruby file (.html.erb) and surround the Ruby code with &lt;% %&gt;
Put the code in an.rb. file and include it in a tag of an HTML file.
Create an embedded Ruby file (.html.erb) and surround the Ruby code with &lt;%= %&gt;.
48. 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
It preloads the images files using asset pipeline.
It selects only portfolios that have an image attached.
It includes the number of associated images when determining how many records to return.
It will execute two database queries of 21 database queries.
49. 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
The galleries table will have no primary key.
The galleries table will include a column named “updated_at”.
The galleries table will contain exactly seven columns.
The galleries table will have an index on the position column.
50. 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 }
This query will result in extensive caching, and you will have to then deal with caching issues.
This query will result in the N+1 query issue. Three orders will result in four queries.
This query will result in the 1 query issue. Three orders will result in one query.
There are no issues with this query, and you are correctly limiting the number of Order models that will be loaded.
Submit