RailsのTips集
RailsのTipsをまとめてみました (2015/01/23)

キャッシュ削除
Rails.cache.delete_matched('*pattern*')
Concern
module PostSearchable
extend ActiveSupport::Concern
included do
end
end
Cache-Controlヘッダの内容
developmentモードの場合
Cache-Control:no-store, must-revalidate, private, max-age=0
productionモードの場合
Cache-Control:max-age=0, private, must-revalidate
does not implement エラーが起きる場合
テスト等でDBのテーブルスキーマを読む前に起きていることがあります。
しょうがないので実行前にFactoryGirl.build
などでモデルオブジェクトを作ったりして回避しています。
Rakeタスクの書き方
# lib/tasks/path/to/sample.rake
desc 'Sample task'
task 'path:to:sample' => :environment do
Rake::Task['path:to:sub_task'].invoke
end
または
desc 'Sample task'
namespace :path do
namespace :to do
task sample: :environment do
Rake::Task['path:to:sub_task'].invoke
end
end
end
JSON <-> Hash相互変換
def params
return @params if @params
@params = JSON.parse(json_params) if json_params
rescue JSON::ParserError
nil
end
def params=(parameter)
assign_attributes(json_params: parameter ? parameter.to_json : nil)
@params = parameter
end
def json_params
json = read_attribute(:json_params)
return json if json
if @params
json = @params.to_json
assign_attributes(json_params: json)
json
end
end
def json_params=(json)
super
@params = nil
json
end
context 'with methods' do
describe '#params' do
before { model.json_params = nil }
its(:params) { should be_nil }
context do
before { model.json_params = '{}' }
its(:params) { should eq({}) }
context do
before { model.json_params = '{"a":1}' }
its(:params) { should eq('a' => 1) }
end
end
end
describe '#json_params' do
before { model.params = nil }
its(:json_params) { should be_nil }
context do
before { model.params = {} }
its(:json_params) { should eq '{}' }
context do
before { model.params = {'a' => 1} }
its(:json_params) { should eq '{"a":1}' }
end
end
end
end
Bulk Insert
posts =
records.map do |record|
Blog::Post.new(record)
end
Blog::Post.import(posts, validate: false, on_duplicate_key_update: [:title])