Railscheatsheet
贡献者:BAI
帮助方法(Helper)
Helper
RUBYclass ApplicationController helper_method :logged_in? def logged_in? "Something" endend
表单
RUBY# http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html- form_for @person do |f| = f.label :first_name = f.label :first_name, "First name" = f.text_field :first_name = f.label :last_name> = f.text_field :last_name> - fields_for @person.permission do |fields| = fields.checkbox :admin -# name="person[admin]" - fields_for :person, @client do |fields| = fields.checkbox :admin = f.submit# 还有: check_box, email_field, fields_for# file_field, hidden_field, label, number_field, password_field# radio_button, range_field, search_field, telephonen_field,# text_area, text_field, url_field
CSS/JS 包
RUBYstylesheet_link_tag :monkeyjavascript_link_tag :monkey
控制器(Controllers)
详见:http://apidock.com/rails/ActionController/Base
Layout
RUBYclass ProjectsController layout 'project' # 默认 layout 名称与 project 名称相同 def save end def edit endend
Before filter
RUBYclass ApplicationController < ActionController::Base before_filter :validate, only: [:save, :edit] before_filter :ensure_auth, except: [:logout] before_filter :require_login private def require_login unless logged_in? flash[:error] = "You must be logged in to access this section" redirect_to new_login_url end endend
默认 URL 选项
RUBYclass ApplicationController < ActionController::Base def default_url_options(options) endend
Hash
RUBYsession[:what]flash[:notice] = "Your session expired"params[:id]
XML 和 JSON
RUBYclass UsersController < ApplicationController def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users} format.json { render :json => @users} end endend
Redirection
RUBYredirect_to action: 'show', id: @entry.idredirect_to root_url
Render
RUBYrender nothing: truerender template: 'products/show'render status: 500render status: :forbiddenrender text: '...'render layout: 'special_layout'render layout: falserender action: 'something'render json: objectrender xml: objectrender location: photo_url(photo)
只返回 head 的响应
RUBYhead :bad_requesthead :created, location: photo_path(@photo)
Layout
RUBY# app/views/layouts/application.html.erb<%= content_for?(:content) ? yield :content : yield %># app/views/layouts/news.html.erb<% content_for :content do %> ...<% end %><% render template: :'layouts/application' %>