- 2009-05-23 (土) 1:57
- Diary | Programming
Wiki なんかだと、 http://sample.com/posts/ほげほげ というリンク先のページが存在しない場合、「ほげほげ」をタイトルとしたページを新規作成するページへ飛ばされたりする。今日はあれを実装したいなー。
# posts_controller.rb
# GET /posts/1
# GET /posts/1.xml
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
rescue ActiveRecord::RecordNotFound
redirect_to :action => :new, :title => params[:id]
end
まず、show アクションをちょろちょろっとイジる。
ここでは、ActiveRecord::RecordNotFound エラーが発生したら、
/posts/new&title=新しいエントリーのタイトル
ページへリダイレクトするようにしている。
ほんとはログイン状態で分岐も作るべきですね(新規作成できるのは普通アカウントを持つユーザーだけっしょ?)。
# GET /posts/1
# GET /posts/1.xml
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
rescue ActiveRecord::RecordNotFound
if logged_in?
redirect_to :action => :new, :title => params[:id]
else
redirect_to :status => 404, :file => 'public/404.html'
end
end
つぎに受け手側である new アクションを編集。
:title を受け取ったら、それを @post.title へセットする。
# GET /posts/new
# GET /posts/new.xml
def new
@post = Post.new
@post.title = params[:title]
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @post }
end
end
ちゃんとセットされてるぞ!でけたっぽい♪
さらに /posts/タイトル でページへアクセスできるように show アクションを書き足してみた。
# GET /posts/1
# GET /posts/1.xml
def show
case params[:id]
when /\d+/
redirect_to :action => :show, :id => Post.find(params[:id]).title
else
@post = Post.find_by_title(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @post }
end
end
rescue ActiveRecord::RecordNotFound
if logged_in?
redirect_to :action => :new, :title => params[:id]
else
redirect_to :status => 404, :file => 'public/404.html'
end
end
タイトルにスペースが入ってるとなんか動きがへんだなぁ…単語が「+」で連結されてしまう。どうやって直そう(@@?
Post.find(params[:id]).title まではちゃんとした空白入りの文字列であるはず。その先の処理で、スペースが「+」になってるんだろうな(それはそれで便利なときがあるのかもしれない)。なので、その箇所でなんらかの処理…おそらくURLエンコードあたりを加えたほうがよさそう。
- Newer: 真のVista厨が生まれる日
- Older: 近所のカレー屋さん

