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_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
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 part of the code below causes the method #decrypt_data to be run?

class MyModel < ApplicationRecord
after_find :decrypt_data
end

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 }

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. Which ActiveRecord query prevents SQL injection?

Reference

Q39. 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

Q40. 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" />

Q41. 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

Q42. Which statement about ActiveRecord models is true?

Q43. 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

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

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

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