linkedin-skill-assessments-quizzes

Ruby on Rails

Q1. When rendering a partial in a view, how would you pass local variables for rendering?

Q2. Within a Rails controller, which code will prevent the parent controller’s before_action :get_feature from running?

Q3. Which statement correctly describes a difference between the form helper methods form_tag and form_for?

Q4. What is before_action (formerly known as before_filter)?

Q5. Which module can you use to encapsulate a cohesive chunk of functionality into a mixin?

Q6. In Rails, which code would you use to define a route that handles both the PUT and PATCH REST HTTP verbs?

Q7. Which choice includes standard REST HTTP verbs?

Q8. Which ActiveRecord query prevents SQL injection?

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

Q10. Are instance variables set within a controller method accessible within a view?

Q11. When a validation of a field in a Rails model fails, where are the messages for validation errors stored?

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”?

-------------------------------

| id | first_name | last_name |
|----|------------|-----------|
| 1  | Alice      | Anderson  |
| 2  | Bob        | Buckner   |
| 3  | Carrie     | Cordero   |
| 4  | Devon      | Dupre     |
| 5  | Carrie     | Eastman   |

-------------------------------

Q13. How would you generate a drop-down menu that allows the user to select from a collection of product names?

Q14. For a Rails validator, how would you define an error message for the model attribute address with the message “This address is invalid”?

Custom Validator

Q15. Given the URL helper product_path(@product), which statement would be expected to be false?

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

Q17. In Rails, how would you cache a partial template that is rendered?

Q18. What is the reason for using Concerns in Rails?

Q19. When using an ActiveRecord model, which method will create the model instance in memory and save it to the database?

Reference

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?

Reference

Q21. In ActiveRecord, what is the difference between the has_many and has_many :through associations?

Q22. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?

Reference

Q23. How would you render a view using a different layout in an ERB HTML view?

Reference

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(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

Reference

class Classroom < ActiveRecord::Base
  belongs_to :students, class_name: 'Student'
end

class Student < ActiveRecord::Base
  belongs_to :classrooms, class_name: 'Classroom'
end
class Student < ActiveRecord::Base
  has_many :classrooms, dependent: true
end

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

class Classroom < ActiveRecord::Base
  belongs_to :student
end
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?

Reference: RoR folder structure

Q28. In Rails, what caching stores can be used?

Q29. What is the correct way to generate a ProductsController with an index action using only the command-line tools bundled with Rails?

Q30. If a model class is named Product, in which database table will ActiveRecord store and retrieve model instances?

Reference

Q32. When Ruby methods add an exclamation point at the end of their name (such as sort!), what does it typically indicate?

Q33. What options below would cause the method #decrypt_data to be run?

class MyModel < ApplicationRecord
  after_find :decrypt_data
end

Reference

Q34. Which Rails helper would you use in the application view to protect against CSRF (Cross-Site Request Forgery) attacks?

Reference

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 }

The before_save callback with the unless: ->(model) { model.is_admin } condition will not be called because the is_admin attribute is true.

The before_destroy callback with the if: ->(model) { model.is_admin } condition will be called if the is_admin attribute is true and the record is being destroyed, but this is not relevant to the scenario of saving the User model.

Therefore, only the after_save callback with the if: ->(model) { model.is_admin } condition will be called in this scenario. This callback will be triggered after the record has been saved, if the is_admin attribute is true. In this case, the clear_cache method will be called.

Q36. In a Rails controller, what does the code params.permit(:name, :sku) do?

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}

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?

class IAmADummy < ActiveRecord::Migration
  def change
    rename_column :accounts, :account_hodler, :account_holder
  end
end
class FixSpellling < ActiveRecord::Migration
  def change
    rename :accounts, :account_hodler, :account_holder
  end
end
class CoffeeNeeded < ActiveRecord::Migration
  def change
    remove_column :accounts, :account_hodler
    add_column :accounts, :account_holder
  end
end
class OopsIDidItAgain < ActiveRecord::Migration
  def rename
    :accounts, :account_hodler, :account_holder
  end
end

Q39. Which HTML is closes to what this code would output?

<% check_box(:post, :visible) %>
<input type="hidden" name="post[visible]" value="0" />
<input type="checkbox" name="post[visible]" value="1" />
<checkbox name="post[visible]" value="1" />
<input type="checkbox" name="post[visible]" value="1" data-default-value="0" />
<input type="checkbox" name="post[visible]" value="1" />

Reference

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

Q41. Which statement about ActiveRecord models is true?

Reference

Q42. What is the correct way to assign a value to the session?

$_SESSION['user_id'] = user.id
@session ||= Session.new << user.id
session_save(:user_id, user.id)
session[:user_id] = user.id

Reference

Q43. Which choice best describes the expected value of @result?

@result = Article.first.tags.build(name: 'Urgent')

Q44. What is the correct syntax for inserting a dynamic title tag into the header of your page from within an ERB view template?

<% render :head do %>
  <title>My page title</title>
<% end %>
<% content_for :head do %>
  <title>My page title</title>
<% end %>
<% render "shared/head, locals: {title: "My page title"} %>
<% tield :head do %>
  <title>My page title</title>
<% end %>

Q45. How would you validate that a project’s name is not blank, is fewer than 50 characters, and is unique?

class Project
  validates :name, presence: true, length: { maximum: 50 }, uniqueness: true
end
class Project
  validate_attribute :name, [:presence, :uniqueness], :length => 1..50
end
class Project
  validate_before_save :name, [:presence, [:length, 50], :uniqueness], :length => 1..50
end
class Project
  validates_presense_of :name, :unique => true
  validates_length_of :name, :maximum => 50
end

Q46. If a product has a user-uploadable photo, which ActiveStorage method should fill in the blank?

class Product << ApplicationRecord
  ____ :photo
end

link_to('Link', {controller: 'products', action: 'index', page: 3})
/products?page=3
/products/index/3
/products/page/3
/products/index/page/3

Q48. Which part of the Rails framework is primarily responsible for making decisions about how to respond to a browser request?

Q49. If User is an ActiveRecord class, which choice would be expected to return an array?

Q50. Which choice is not a valid Rails route?

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?

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 = _____

Reference

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 }

Q54. Which choice is an incorrect way to render a partial?

Q55. Which code sample will skip running the login_required “before” filter on the get_posts controller action?

Q56. Within a Rails model with a cache_key method, which code snippet will expire the cache whenever the model is updated?

after_update_commit do
destroy
end
after_destroy do
Rails.cache.delete(cache_key)
end
after_update_commit do
Rails.cache.delete(cache_key)
end
after_update_commit do
Rails.cache.destroy(cache_key)
end

Reference

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

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
rescue => e
  logger.info e
end
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response
rescue ActiveRecord::RecordNotFound
  render json: { message: 'User not found' }, status: :not_found
end
raise ActiveRecord::RecordNotFound
  render json: { message: 'User not found' }, status: :user_not_found
end

Q59. What decides which controller receives which requests?

Q60. When rendering a partial in a view, how would you pass local variables for rendering?

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

Reference Reference

Q62. Where would this code most likely be found in a Rails project?

scope :active, lambda { where(:active => true) }

Q63. What is a standard prerequisite for implementing Single Table Inheritance (STI)?

Q64. A way that views can share reusable code, such as formatting a date, is called a _?

Q65. How do you add Ruby code inside Rails views and have its result outputted in the HTML file?

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

Q67. What is RVM?

Q68. Which line of inquiry would you follow after receiving this error message: No route matches [POST] “/burrito/create”?

Q69. Which controller action is not in danger of returning double render errors?

def show
  if params[:detailed] == "1"
    redirect_to(action: 'detailed_show')
  end
  render('show')
end
def show
  render('detailed_show') if params[:detailed] == "1"
  render('show') and return
end
def show
  if params[:detailed] == "1"
    render('detailed_show')
  end
  render('show')
end
def show
  if params[:detailed] == "1"
    render('detailed_show')
  end
end

Q70. Which keyword is used in a layout to identify a section where content from the view should be inserted?

Reference

Q71. Check the following Ruby code and replace __BLOCK__ with the correct code to achieve the result.

class TodoList
  def initialize
    @todos = []
  end

  def add_todo(todo)
    @todos << todo
  end

  def __BLOCK__
    @todos.map { |todo| "- #{todo}" }.join("\n")
end

work = TodoList.new
work.add_todo("Commit")
work.add_todo("PR")
work.add_todo("Merge")

puts work
=> - Commit
=> - PR
=> - Merge

Q72. What decides which controller receives which requests?

Q73. Which statement about this code will always be true?

class UserController < ActionController::Base
  def show
    @user = User.find_by_id(session[:user_id])
    @user ||= User.first
  end
end

Reference #Assignment_Operators

Q74. When defining a resource route, seven routes are defined by default. Which two methods allow defining additional routes on the resource?

Q75. You are rendering a partial with this code. What will display the user’s name?

<%= render partial: 'user_info', object: { name: 'user' } %>

Q76. Once this form is submitted, which code in the controller would retrieve the string for :name?

<%= form_for(@category) do |f| %>
  <%= f.text_field(:name) %>
<% end %>

Reference

Q77. Which missing line would best show the correct usage of strong parameters?

class ProjectsController < ActionController::Base

  def create
    Project.create(project_params)
  end

  private

  def project_params
    # Missing line
  end
end

Strong Params

Q78. What is the purpose of the rake db:migrate command?

Reference

Q79. What is the execution result of the following Ruby code?

class A
  def self.get_self
    self.class
  end

  def get_self
    self
  end
end

p "#{A.get_self.class} #{A.new.get_self.class}"

Reference

Q80. Given the following model class and view , which code snippet should you use to fetch the correct results, and avoid the N+1 query issue?

class Movies < ApplicationRecord
  def recent_reviews
    # Return the latest 10 reviews
  end
end
<%= @movie.recent_reviews.each do |review| %>
  <div>
    <header><%= review.critic.name %></header>
    <div><%= review.comment %></div>
  </div>
<% end %>

Reference