maeshimaの日記

メモ書きです

今週のrailscasts - Controllers in Rails 3

Railscasts - Controllers in Rails 3
ASCIIcasts - “Episode 224 - Controllers in Rails 3”

を見て。

filter_parameter_logging

filter_parameter_logging の設定が application.rb に移行。

config.filter_parameters += [:password]

のような設定方法になった。

redirect_to

flash が reditect の引数で渡せるようになった(:notice と :alert だけかも)。ちなみにこれは2.3.6以降でも使える。

redirect_to @product, :notice => "Successfully created product."

下記の二つは同じ。これも 2.3.6 以降はつかえるみたい

redirect_to edit_product_path(@product)
redirect_to [:edit, @product]

nested resource な path へのリダイレクトも下記のように書ける。

redirect_to [@category, @product]

上記のような書き方は link_to とかでも使える

cookies

permanentなcookieが作れるようになった。2.3.6 以降でも使える。

# これまでのやりかた
cookies[:last_product_id] = {:value => @product_id, :expires => 1.month.from_now}
# 2.3.6以降
cookies.permanent[:last_product_id] = @product.id

respond_to

respond_to が書きやすくなった。これまでだとすべてのactionにrespond_toの定義を書かなきゃ行けなくてめんどかった。

下記のように respond_to のところに対応すべき拡張子を設定して、respond_withで返却するオブジェクトを指定するような形式になった。

   respond_to :html, :xml

   def index
     @products = Product.all
     respond_with @product 
     end
   end

respond_with は拡張子にあわせて to_xml したり to_json したりしてくれる。

また、create したときの respond_with は、オブジェクトがエラーかどうかで render したり redirect したりとよしなにしてくれる。update や destroy の時も空気を読んでredirect_to 等してくれる。

ただ、redirectするときのURLを下記のように指定することも出来る。

respond_with @product, :location => products_url
respond_with(@proeuct, :responder => MyResponder)

のようにして、respondの挙動を自分で作ることも出来るみたい。