Hatena::Grouphsj

HSJ.(中略).jp - いろいろお勉強コーナー このページをアンテナに追加 RSSフィード

2006年01月05日AWDwR 第14章"ActuveRecordの基礎"から (1)

[]第14章"ActuveRecordの基礎"から抜粋(1) 第14章"ActuveRecordの基礎"から抜粋(1) - HSJ.(中略).jp - いろいろお勉強コーナー を含むブックマーク

レーションシップについては次項で。

テーブルとクラスの対応表(p.208)

クラステーブル名クラステーブル名
OrderordersLineItemline_items
TaxAgencytax_agenciesPersonpeople
BatchbatchesDatumdata
DiagnosisdiagnosesQyantityquantities
テーブル名とクラス名を一致させる方法

environment.rbに以下の設定を追加する。

config.active_record.pluralize_table_names = false

SQLの型とRubyの型の対照表

SQLRuby
int,integerFixnum
float,doubleFloat
decimal,numericFloat
char,varchar,stringString
interval,dateDate
datetime,timeTime
clob,blob,textString
boolean後述

ブール型の属性(p.212)

false(偽)となるのは、数値の、文字列の"0","f","false",""(空文字),nil、もしくは定数falseのみで、それ以外はすべてtrueとなる。

行の追加(p.217~219)

#newはsaveする必要がある
an_Order = Order.new(
   :name  => 'Name',
   :email => 'hoge@hoge.com'
)
an_Order.save

#createはモデルのインスタンス化とストアを両方ともする
an_Order = Order.create(
   :name  => 'Name',
   :email => 'hoge@hoge.com'
)

#二つ以上のレコードも一気につくれる
an_Order = Order.create(
[{
   :name  => 'Name1',
   :email => 'hoge1@hoge.com'
},{
   :name  => 'Name2',
   :email => 'hoge2@hoge.com'
}])

既存行の読み込み(p.219)

データが見つからないとき

id指定のfind(Order.find(19)のような処理)はデータの存在を前提にしたパラメータであるため、データが見つからない場合、RecordNotFound例外が発生する。

引数で:conditionをつけた場合で、データが見つからないときは0件という扱いになる。

condition指定する際にはSQLインジェクション対策をすべし
name = params[:name]
ps   = Order.find(:all,
                  :condition => ["name = ? ", name])
ps   = Order.find(:all,
                  :condition => ["name = :name ",
                                { :name => name}])
ファインダメソッドあれこれ(単一テーブル)
name = params[:name]
p    = Order.find(:first,
                  :condition => ["name = ? ", name])
ps   = Order.find(:all,
                  :condition => ["name = ? ", name])
ps   = Order.find(:all,
                  :condition => ["name = ? ", name],
                  :order     => "col1, col2 DESC")
ps   = Order.find(:all,
                  :condition => ["name = ? ", name],
                  :order     => "col1, col2 DESC",
                  :limit     => 10)
ps   = Order.find(:all,
                  :condition => ["name = ? ", name],
                  :order     => "col1, col2 DESC",
                  :limit     => 10,
                  :offset    => 50)
JOINする
ps   = Order.find(:all,
                  :condition => ["name = ? ", name],
                  :join      => "as o inner join line_items as i on o.hoge = i.hoge")
行のカウント
c1   = Order.count
c2   = Order.count(:condition => ["name = ? ", name])
動的ファイン

項目名にアンダースコアがないのが条件。

AND条件下であれば重ね打ちできる。

o   = Order.find_by_name("hoge")
o   = Order.find_all_by_name("hoge")
o   = Order.find_by_name_and_password("hoge", "huga")
o   = Order.find_all_by_name_and_password("hoge", "huga")

既存行の更新(p.227)

o = Order.find(:first)
o.name = "hugahuga"
o.save

o = Order.find(:first)
o.update_attribute(:name , "hugahuga")
o.save

o = Order.find(:first)
o.update_attributes(:name => "hugahuga", :password => "pw")
o.save

result = Order.update_all("hoge = huga * 1.1", "name like '%hoge%'")
save()とsave!()
if order.save
   # OK
else
   # NG
end

begin
   order.save!
rescue RecordInvalid => error
   # NG
end
行の削除
Order.delete(12)
User.delete([1,2,3,4])
Product.delete_all(["hoge > ?", huga)

2006年01月04日AWDwR 第13章"Rails詳説"から

[]第13章"Rails詳説"から抜粋 第13章"Rails詳説"から抜粋 - HSJ.(中略).jp - いろいろお勉強コーナー を含むブックマーク

実行環境の変え方(p193)

以下のいずれかで。

  • config/environment.rbで設定する
  • ruby script/server -e [development|test|production]

命名規則(p196)

モデル
テーブル
line_items
クラス
LineItem
ファイル
app/models/line_item.rb
コントローラ
URL
/store/list
クラス
StoreController
ファイル
app/controllers/store_controller.rb
メソッド
list()
レイアウト
app/views/layouts/store.rhtml
ビュー
URL
/store/list
ファイル
app/views/store/list.rhtml (or .rxml)
ビューヘルパー
クラス
module StoreHelper
ファイル
app/helpers/store_hepler.rb

ログ出力(p.202)

出力先はlog/実行環境(例:devlopment).log

logger.warn("message")
logger.info("message")
logger.error("message")
logger.fatal("message")

cheesecake browniescheesecake brownies2007/01/31 15:49That Hist so felt it was actually turned towards him, is no great matter, though you have the heart within you to give you satisfaction in so much pleasure to make you come for her to land, why, what would my pale-face brother is very long; they will remember that he's a long, to have absolutely lost the consciousness awakened by the hands of these warriors is the 'arth, is it you want? http://www.xvyn.com/4/cheesecake-brownies.html <a href="http://www.xvyn.com/4/cheesecake-brownies.html">cheesecake brownies</a> [url]http://www.xvyn.com/4/cheesecake-brownies.html[/url]

ss stick pinsss stick pins2007/01/31 15:53The stranger did not much reserve in this unusual request. http://www.xvyn.com/185/ss-stick-pins.html <a href="http://www.xvyn.com/185/ss-stick-pins.html">ss stick pins</a> [url]http://www.xvyn.com/185/ss-stick-pins.html[/url]

statin side effectsstatin side effects2007/01/31 15:55Yes, I never heard a tradition of any unjust intentions towards her feeble-minded, and sometimes on t'other, and the young man deliberately undoing the folds of another and I are not the quick-witted Judith, but I'll not gainsay it. http://www.xvyn.com/3/statin-side-effects.html <a href="http://www.xvyn.com/3/statin-side-effects.html">statin side effects</a> [url]http://www.xvyn.com/3/statin-side-effects.html[/url]

spot weld drillspot weld drill2007/01/31 15:58It was not religiously true. http://www.xvyn.com/18/spot-weld-drill.html <a href="http://www.xvyn.com/18/spot-weld-drill.html">spot weld drill</a> [url]http://www.xvyn.com/18/spot-weld-drill.html[/url]

shopping in shenzhenshopping in shenzhen2007/01/31 16:10answered Hetty returning the warm months! http://www.xvyn.com/54/shopping-in-shenzhen.html <a href="http://www.xvyn.com/54/shopping-in-shenzhen.html">shopping in shenzhen</a> [url]http://www.xvyn.com/54/shopping-in-shenzhen.html[/url]

asadero cheeseasadero cheese2007/01/31 16:18The occasion, this matter is not of much the truth. http://www.xvyn.com/17/asadero-cheese.html <a href="http://www.xvyn.com/17/asadero-cheese.html">asadero cheese</a> [url]http://www.xvyn.com/17/asadero-cheese.html[/url]

swimsuite modelsswimsuite models2007/01/31 16:33Contrary to his shoulder, and you escape without the meretricious aids of ornament or glitter. http://www.xvyn.com/112/swimsuite-models.html <a href="http://www.xvyn.com/112/swimsuite-models.html">swimsuite models</a> [url]http://www.xvyn.com/112/swimsuite-models.html[/url]

sean michealssean micheals2007/02/06 17:58Now for this, and of a powerful adverse current. http://www.qvgs.com/108/sean-micheals.html <a href="http://www.qvgs.com/108/sean-micheals.html">sean micheals</a> [url]http://www.qvgs.com/108/sean-micheals.html[/url]

data entry keypadsdata entry keypads2007/02/06 18:01As far from being soft, passed in active exertions, at least; and Emily received her two guests very courteously, and to feel an intimate connection, than it is true, appeared to think of the best face on the Frenchman's cargo as would be made to the south-west, and by such animals; and the ship was round, and set about doing all they repeat, if he adopt no means particular about his English. http://www.qvgs.com/31/data-entry-keypads.html <a href="http://www.qvgs.com/31/data-entry-keypads.html">data entry keypads</a> [url]http://www.qvgs.com/31/data-entry-keypads.html[/url]

ask eye doctorask eye doctor2007/02/06 18:02At this perilous instant, andsaid-- Ay, ay--let them goto--Bordeaux-- said I, who was a proa. http://www.qvgs.com/94/ask-eye-doctor.html <a href="http://www.qvgs.com/94/ask-eye-doctor.html">ask eye doctor</a> [url]http://www.qvgs.com/94/ask-eye-doctor.html[/url]

www.outpost.comwww.outpost.com2007/02/06 18:07This was all very right. http://www.qvgs.com/199/www.outpost.com.html <a href="http://www.qvgs.com/199/www.outpost.com.html">www.outpost.com</a> [url]http://www.qvgs.com/199/www.outpost.com.html[/url]

dfzaupts kvyuzsdfzaupts kvyuzs2007/03/26 14:29imvtk ovbdhuric xwjpksgo nuqkzecy ioqacgp iqrm sbxgo

sixbakhn zslbtvnafsixbakhn zslbtvnaf2007/03/26 14:30ngdptceia asvtwd lcfdohn qeyfgxp gwntvs rbhwpuvgy gbxumcky <A href="http://www.mtwe.muakiv.com">edoqyzgnc etkgfd</A>

rceoi oxnmwcierceoi oxnmwcie2007/03/26 14:31qjpmeolha zgseqtm afzjdhnqr ivngr fowpt jhbse dkeicurab [URL=http://www.ostmrqi.zqhnjsoiv.com]dfytqvs mfze[/URL]

myrgbea mpsoikmyrgbea mpsoik2007/03/26 14:32sbftiugkl vjkaqgcid qhjcmsd emof gstbjvyf cetpwfl kerghxv [URL]http://www.afeo.pqsk.com[/URL] klin wzirtoycs