個人的なメモ・備忘録



Tips

ActiveRecord::BaseオブジェクトからURLへのクエリーのための属性のハッシュを取得する方法

Hash[*Hoge.column_names.map{|key|["hoge[#{key}, hoge.send(key)]"].flatten}]

link_toなどで使い場合は以下のように
link_to("next", {:controller => :hoges, :action => :list}.merge(ここに上記のハッシュ))

cygwinでユーザ名に日本語を使うと、プログラムのインストールなどに支障が出る。

cygwin/mysql の環境では、config/database.yml での host の指定を、LOCALHOST と大文字にしておく必要がある。

DreamWeaverでeruby用の拡張

全体の設定ファイルではなく、ユーザ毎の設定ファイル(Documents and Settings以下)を修正する必要がある。

変数の各種変換(参照:http://d.hatena.ne.jp/motoyasu_yamada/20070214 )

単数<->複数の変換ルールはactivesupport/lib/active_support/inflector.rbにて定義されている。
コマンド概要
pluralize単語を複数形にする"person".pluralize #=> "people"
singularize複数形を単数形にする"people".singularize #=> "person"
camelizeキャメル表記にする"camel_case".camelize #=> "CamelCase"
titleizeアンダースコア・空白を除去し、全単語の頭を大文字にする"title_string".titleize #=> "Title String"
underscoreキャメル表記をアンダースコア表記に"UnderScore".underscore #=> "UnderScore"
dasherizeアンダースコアをハイフンに"hoge_hoge".dasherize #=> "hoge-hoge"
humanize文章っぽい表記に。"employee_salary".humanize #=> "Employee salary"
"author_id".humanize #=> "Author"
demodulizeJavaでいうFQDNをクラス名に"ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
classifyテーブル名からクラス名を(singularize&camelize)"tests".classify #=> "Test"
tableizeクラス名からテーブル名を(underscore&pluralize)"Test".tableize #=> "tests"
foreign_key外部キー名に"Message".foreign_key #=> "message_id"
ordinalize数値を順表記にする1.ordinalize #=> "1st"
constantize文字列から定数を作成する。Module.const_get(string)と同じ。"Foo".constantize #=> class Foo

テーブル作成時に、created_at,updated_at,create_by,updated_byを自動で追加する

以下のコードをconfig/environment.rbに追加。
 module ActiveRecord
   module ConnectionAdapters
     module SchemaStatements
       def create_table_with_datetime_columns(*args)
         create_table_without_datetime_columns(*args) do |t|
           yield t
           # ブロック呼んだ後でシステムカラムの追加
           t.datetime_columns
           t.editor_columns
         end
       end
       alias_method :create_table_without_datetime_columns, :create_table
       # create_table を置き換えたくない場合は次の行をコメントアウト
       alias_method :create_table, :create_table_with_datetime_columns
     end
 
     class TableDefinition
       # 新しいメソッドを追加
       def datetime_columns
         column "created_at", :timestamp
         column "updated_at", :timestamp
       end
       def editor_columns
         column "created_by", :integer
         column "updated_by", :integer
       end
     end
   end
 end

remote_functionにtext_fieldの値を渡す方法

<input type="text" name="textfield" id="textfield" onchange="<%= remote_function(:update => "target", :url => {:action => :update_target}, :with => "'param='+ escape(value)") %>">
この:withで指定した文字列はjavascriptとして評価されるので、escape(value)とすることで呼び出しもとのtext_fieldの値this.valueが渡される。

SQL文の直接実行方法

 ActiveRecord::Base.connection.execute([SQL文])

クエリの内容に応じて以下の方法を使うと、戻り値として影響のあった件数を取得できる
 ActiveRecord::Base.connection.update([SQL文])
 ActiveRecord::Base.connection.insert([SQL文])
 ActiveRecord::Base.connection.delete([SQL文])

実行環境の選択

 $ ruby ./script/server -e production 
 $ ruby ./script/console production  
 $ rake db:migrate RAILS_ENV=production

ActiveRecordにて、値の変更を制御するメソッド

changed?モデルの値を変更したか否か
[カラム名]_changed?モデルの指定したカラム名の値を変更したか否か
[カラム名]_wasモデルの指定したカラム名の変更前の値
[カラム名]_changeモデルの指定したカラム名の変更前と後の値のリスト。変更が内場合はnil
changedモデルの変更したカラム名のリスト
changesモデルの変更したカラム名をキーとする変更前と後の値のリスト
{"key1" => ["before", "after"], "key2" => [1,2]}
[カラム名]_will_change!=以外のメソッドでカラム名の値を変更した場合に、変更を宣言する

AciveRecordのupdateにて、変更のないカラムを除外する設定

ActiveRecord::Base.partial_updates = true

ActiveRecordで集計処理を行いたい場合

ActiveRecord::Calculationsというモジュールを対象のModelクラスにミックスインする
class Foo < ActiveRecord::Base
   include ActiveRecord::Calculations
end

以下の関数が利用可能
average平均値を求める
countカウント
maximum最大値
minimum最小値
sum集計値
Foo.sum("bar") #=> カラムbarの合計
Foo.count(:conditions => ["created_at >= ?", Time.now.last_month]) #=> 過去一ヶ月に作成されたデータの件数

データベースの内容をYMLファイルに変換

ARClass.find(:all).collect{|record| record.attributes.to_yaml}

ActiveRecordの各種コールバック関数の呼び出し順

挿入の場合
  1. before_validation
  2. before_validation_on_create
  3. # ここで validation が行われる
  4. after_validation
  5. after_validate_on_create
  6. before_save
  7. before_create
  8. # ここで DB に挿入される
  9. after_save
  10. after_create
更新の場合
  1. before_validation
  2. before_validation_on_update
  3. # ここで validation が行われる
  4. after_validation
  5. after_validate_on_update
  6. before_save
  7. before_update
  8. # ここで DB が更新される
  9. after_save
  10. after_update
削除の場合
  1. before_destroy
  2. # ここで DB から削除される
  3. after_destroy

時間のかかっている処理トップテンを探す

$ grep Completed [ログファイル名] | sort -nr -k 3 | head -10

ActiveRecordで抽象クラスを定義する

self.abstract_class = true

ActiveRecordで規約に沿わないテーブルとつなげる

self.set_table_name = [テーブル名]

このページへのコメント

rmpEco Im grateful for the blog article.Thanks Again. Will read on...

0
Posted by awesome things! 2014年01月20日(月) 19:10:28 返信

ssVNTD Very neat blog post.Really looking forward to read more. Much obliged.

0
Posted by stunning seo guys 2013年12月31日(火) 13:30:35 返信

8LTq6m Thanks for the article post.Much thanks again. Great.

0
Posted by tips about seo 2013年12月19日(木) 10:41:50 返信

EeaMn3 <a href="http://qipbxhqdmvuk.com/">qipbxhqdmvuk</a>, [url=http://dixknhvmstjq.com/]dixknhvmstjq[/url], [link=http://clvepimxmlfz.com/]clvepimxmlfz[/link], http://lwczdqpoyehe.com/

0
Posted by wlkozhnyiq 2013年11月19日(火) 17:44:23 返信

9rGIl1 <a href="http://avolvrxnrjef.com/">avolvrxnrjef</a>, [url=http://tyjscupqhmgj.com/]tyjscupqhmgj[/url], [link=http://cstqutfvulzv.com/]cstqutfvulzv[/link], http://cqhcnrnqpkje.com/

0
Posted by zgprmxb 2013年11月15日(金) 11:11:51 返信

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Wiki内検索

編集にはIDが必要です