3.2.x系を使用してます。
View
named helperでクエリストリング追加
hoge_path(@resource, :unko => 'deru')
# => /hoge?unko=deru
単数形リソースでform_forした場合に undefined_method
routes.rb
resource :user
このように単数形リソースにした場合、
form_for @user do |f|
そのままform_forするとエラー。
undefined_method 'user_path'
かといって resource :users
とするのも何か悔しい。
form_for @user, :url => user_path do |f|
で解決。
http://stackoverflow.com/questions/3736759/ruby-on-rails-singular-resource-and-form-for
https://github.com/rails/rails/issues/1769#issuecomment-9556381
Controller
add_to_base は :base になりました
errors.add :base, "message"
レイアウトを変更する
def HogeController < ApplicationController
# fugaアクションだけにする場合
layout "no_menu", :only => :fuga
end
例外を補足してエラー用アクションへ
def HogeController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, :with => :error_404
def error_404
render :template => '/pages/error_404', :status => 404
end
end
全リンクにlocale情報をセットする
class ApplicationController < ActionController::Base
def default_url_options(options={})
# jaの場合は省略
unless I18n.locale == :ja
return { :locale => I18n.locale }
end
options
end
# 既定のロケールをセット
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
参考: http://morizyun.github.io/blog/i18n-english-rails-ruby-many-languages/
basic認証
http_basic_authenticate_with :name => "admin", :password => "abcdefg"
Mailer
メールを送信する
app/mailer/user_mailer.rb
class UserMailer < ActionMailer::Base
default from: "from@example.com", bcc: "bcc@example.com", to: "to@example.com"
def registration(user)
@user = user
mail(:to => @user.email, :subject => "Registration")
end
end
controller
UserMailer.registration(user).deliver
helperをmailerでも
class FooBarMailer < ActionMailer::Base
helper :hoge, :application
end
その他
developmentでも環境によって設定を変えたい
やりかたは色々あると思いますが、作業者ごとのサーバーで分けたかったのでENV["HOME"]
で分岐することにしました。
config/environments/development.rb
if ENV["HOME"].match(/akkunchoi/)
config.action_mailer.perform_deliveries = false
config.action_mailer.default_url_options = { :host => 'hoge.dev' }
config.action_mailer.raise_delivery_errors = true
else
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => 'example.jp' }
config.action_mailer.raise_delivery_errors = true
end
属性名を読みやすい形に変換
Person.human_attribute_name("first_name") # => "First name"