[PRESS 0008] Sample Application (BLOG) の作成 [3rd]
RAILS PRESS » [PRESS 0007] Sample Application (BLOG) の作成 [2nd]の続きを。
モデルの関連づけ
今回はモデル間の関連を定義して、エントリー投稿時に投稿ユーザとエントリーを関連づけるようにします。
まずapp/model/user.rbに以下の記述を追加。
この記述でUserモデルがEntryおよびCommentとそれぞれ1対多の関係になります。
-
require 'digest/sha1'
-
-
# this model expects a certain database layout and its based on the name/login pattern.
-
class User <ActiveRecord::Base
-
has_many :entries
-
has_many :comments
-
-
:
-
:
-
end
次にこれに対応する記述をEntryモデルとCommentモデルにも記述します。
-
class Entry <ActiveRecord::Base
-
belongs_to :user
-
end
-
class Comment <ActiveRecord::Base
-
belongs_to :user
-
end
これで各モデルに対して、
-
@user.entries <<@entry
-
@user.comments <<@comment
-
@entry.user = @user
-
@comment.user = @user
のように関連を付けることができます。それでは早速コントローラ側でこの関連づけの設定をしてみましょう。
app/controllers/entries_controller.rb内のcreateアクションとupdateアクションで、それぞれ以下の3行目の定義を加えます。
-
def create
-
@entry = Entry.new(params[:entry])
-
@entry.user = @session[:user]
-
if @entry.save
-
flash[:notice] = 'Entry was successfully created.'
-
redirect_to :action => 'list'
-
else
-
render :action => 'new'
-
end
-
end
-
def update
-
@entry = Entry.find(params[:id])
-
@entry.user = @session[:user]
-
if @entry.update_attributes(params[:entry])
-
flash[:notice] = 'Entry was successfully updated.'
-
redirect_to :action => 'show', :id => @entry
-
else
-
render :action => 'edit'
-
end
-
end
これでUserとEntryの関連づけができるようになりました。同様にEntryとCommentの関連付けもしてやれば、一通りの骨組みはできあがり。(かな?)
ということで、練習はこんなものでおしまいにしますか。
About this entry
You’re currently reading “ [PRESS 0008] Sample Application (BLOG) の作成 [3rd] ,” an entry on RAILS PRESS
- Published:
- 1.5.07 / 6pm
- Category:
- practice
No comments
Jump to comment form | comments rss [?] | trackback uri [?]