<%= 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_featureskip :get_feature, except: []prevent_action :get_feature:redis_cache_storeform_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::ConcernRailsHelper.CommonClassActiveJob::MixinActiveSupport::ModulePUT and PATCH REST HTTP verbs?put :items, include: patchput 'items', to: 'items#update'match 'items', to 'items#update', via: [:put, :patch]match :items, using: put && patchProduct.where("name = #{@keyword}")Product.where("name = " << @keyword}Product.where("name = ?", @keywordProduct.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.errormy_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 invaliderrors(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: truerender_with_cache partial: 'shared/menu'render partial: 'shared/menu'render partial: 'shared/menu', cached_with_variables: {}buildnewcreatesavecoffee_orders. What would the ActiveRecord model be named in order to use that table?CoffeeOrdersCoffee_OrdersCoffee_OrderCoffeeOrderhas_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_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
Reference: RoR folder structure
<script src="/main.js"></script><%= javascript_include_tag 'main' %><%= javascript_tag 'main' %><!-- include_javascript 'main' -->rails generate controller --options {name: "Products", actions: "index"}rails generate controller --name Products --action indexrails generate controller Products indexrails generate ProductsController --actions indexproduct_tableall_productsproducts_tableproductssort!), 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.destroyMyModel.new(field: 'new instance')csrf_protectioncsrf_helpercsrf_meta_tagscsrfUser 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_dataclear_cachenotify_admin_usersis_admin is true.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
decrypt_data to be run?class MyModel < ApplicationRecord
after_find :decrypt_data
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
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.<%= render partial: 'user_info', object: { name: 'user' } %>
<%= locals.user_info.name %><%= object.name %><%= @user.name %><%= @user_info.name %><%= form_for(@category) do |f| %>
<%= f.text_field(:name) %>
<% end %>
params[:name]@params.nameparams.require(:category).permit(:name)params[:category][:name]