<%= render partial: "nav", selected: "about"}%> <%= render partial: "nav", local_variables: {selected: "about"} %> <%= render partial: "nav", locals: {selected: "about"} :get_feature from running?skip_before_action :get_feature skip :get_feature, except: [] prevent_action :get_feature :redis_cache_store form_tag and form_for?form_tag method is for basic forms, while the form_for method is for multipart forms that include file uploads. form_tag method is for HTTP requests, while the form_for method is for AJAX requests. form_tag method typically expects a URL as its first argument, while the form_for method typically expects a model object. form_tag method is evaluated at runtime, while the form_for method is precompiled and cached. before_action (formerly known as before_filter)?ActiveSupport::Concern RailsHelper.CommonClass ActiveJob::Mixin ActiveSupport::Module 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 Product.where("name = #{@keyword}") Product.where("name = " << @keyword} Product.where("name = ?", @keyword Product.where("name = " + h(@keyword) 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
:type. :documentable_id and :documentable_type. :documentable and :type. :polymorphic_type. my_model.errors[:field] my_model.get_errors_for(:field) my_model.field.error my_model.all_errors.select(:field) 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 |
-------------------------------
User.where(first_name: "Carrie") User.not.where(id: [1, 2, 4, 5]) User.find_by(first_name: "Cordero") User.find(3) <%= select_tag(@products) %> <%= collection_select(@products) %> <select name="product_id"> <%= @products.each do |product| %> <option value="<%= product.id %>"/> <% end %></select> <%= collection_select(:product, :product_id, Product.all, :id, :name) %> address with the message "This address is invalid"?model.errors = This address is invalid errors(model, :address) << "This address is invalid" display_error_for(model, :address, "This address is invalid") model.errors[:address] << "This address is invalid" product_path(@product), which statement would be expected to be false?class DocumentsController < ApplicationController before_action :require_login def index @documents = Document.visible.sorted end end
:index is not listed as an argument to before_action. require_login method will automatically log in the user before running the index action. require_login method calls render or redirect_to. render partial: 'shared/menu', cached: true render_with_cache partial: 'shared/menu' render partial: 'shared/menu' render partial: 'shared/menu', cached_with_variables: {} build new create save coffee_orders. What would the ActiveRecord model be named in order to use that table?CoffeeOrders Coffee_Orders Coffee_Order CoffeeOrder has_many and has_many :through associations?has_many: through association is the one-to-many equivalent to the belongs_to one-to-one association. has_many: through is maintained only for legacy purposes. 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. has_many :through, the declaring model can associate through a third model. <% %>. <% %>. The web server will handle the rest. <%= %>. <link> tag of an HTML file. <% render 'view_mobile' %> <% render 'view', use_layout: 'mobile' %> <% render 'view', layout: 'mobile' %> <% render_with_layout 'view', 'mobile' %> 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
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
<%= javascript_include_tag 'main' %> <%= javascript_tag 'main' %> <!-- include_javascript 'main' --> 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 product_table all_products products_table products sort!), what does it typically indicate?#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') csrf_protection csrf_helper csrf_meta_tags csrf 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 is_admin is true.
[Explanation]:
When saving the User model and model.is_admin is set to true, the after_save callback will be called. 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.
params.permit(:name, :sku) do?:name or :sku to make forms more secure. :name or :sku are found. :name and :sku parameters are set to nil. sort method executes properly?[5,8,2,6,1,3].sort {|v1,v2| v1 ___ v2}
=> <==> <=> || 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
<% 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" />
class AccessController < ActionController::Base
def destroy
session[:admin_id] = nil
flash[:notice] = ""You have been logged out""
render('login')
end
$_SESSION['user_id'] = user.id
@session ||= Session.new << user.id
session_save(:user_id, user.id)
session[:user_id] = user.id
@result = Article.first.tags.build(name: 'Urgent')
<% 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 %>
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
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
class Category < ActiveRecord::Base
# has a database column for :name
end
category = Category.first
category.name = 'News'
saved_name = _____
class LineItem < ApplicationRecord
end
class Order < ApplicationRecord
has_many :line_items
end
Order.limit(3).each { |order| puts order.line_items }
<%= render(:partial => 'shared/product') %> <%= render('shared/product', :collection => @products) %> <%= render(template: 'shared/product', with: @products) %> <%= render('shared/product', locals: { product: @product }) %> login_required "before" filter on the get_posts controller action?before_action :login_required, skip: [:get_posts] skip_before_action :login_required, except: [:get_posts] skip_before_action :login_required, only: [:get_posts] skip_action before: :login_required, only: [:get_posts] 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
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
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
<%= render partial: "nav", globals: {selected: "about"} %> <%= render partial: "nav", local_variables: {selected: "about"} %> <%= render partial: "nav", locals: {selected: "about"} %> <%= render partial: "nav", selected: "about"} %> @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) scope :active, lambda { where(:active => true) }
ActiveRecord::STI <% %>. The web server will handle the rest. (.html.erb) and surround the Ruby code with <% %> an.rb. file and include it in a <link> tag of an HTML file. (.html.erb) and surround the Ruby code with <%= %>. @portfolios = Portfolio.includes(:image).limit(20)
@portfolios.each do |portfolio|
puts portfolio.image.caption
end
post route that matches "/burrito/create" in your routes.rb file. resources :burritos to your routes.rb file. get route that matches "burrito/create" in your paths.rb file. 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
__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
class UserController < ActionController::Base
def show
@user = User.find_by_id(session[:user_id])
@user ||= User.first
end
end
@user will be set to the object returned by User.first unless session[:user_id] has a value. User.find_by_id is irrelevant because the variable @user will always be set to the object returned by User.first. User.find_by_id does not raise an exception, the variable @user will be set to the object returned by User.first. User.find_by_id returns nil or false, the variable @user will be set to the object returned by User.first. Reference #Assignment_Operators
<%= render partial: 'user_info', object: { name: 'user' } %>
<%= locals.user_info.name %> <%= object.name %> <%= object[:name] %> <%= @user.name %> <%= form_for(@category) do |f| %>
<%= f.text_field(:name) %>
<% end %>
params[:name] @params.name params.require(:category).permit(:name) params[:category][:name] class ProjectsController < ActionController::Base
def create
Project.create(project_params)
end
private
def project_params
# Missing line
end
end
params[:project].allow(:name, :visible, :description) params[:project].allowed params.permit(:project).allow(:name, :visible, :description) params.require(:project).permit(:name, :visible, :description) To create a new database for the Rails application. To migrate the database schema to the latest version. To seed the database with initial data. To test the database connection. 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}"
Class Class A A A Class Class A 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 %>
@movie.reviews.order(created_at: :desc).limit(10) @movie.reviews.joins(:critic).order(created_at: :desc).limit(10) @movie.reviews.includes(:critic).order(created_at: :desc).limit(10) @movie.reviews.references(:critic).order(created_at: :desc).limit(10)