この記事をはてなブックマークに登録 この記事のはてなブックマーク数 この記事を livedoor クリップに登録この記事の livedoor クリップ数 この記事を Buzzurl に登録 この記事の Buzzurl ブックマーク数

[PRESS 0008] Sample Application (BLOG) の作成 [3rd]


RAILS PRESS » [PRESS 0007] Sample Application (BLOG) の作成 [2nd]
の続きを。

モデルの関連づけ

今回はモデル間の関連を定義して、エントリー投稿時に投稿ユーザとエントリーを関連づけるようにします。
まずapp/model/user.rbに以下の記述を追加。
この記述でUserモデルがEntryおよびCommentとそれぞれ1対多の関係になります。

RUBY:
  1. require 'digest/sha1'
  2.  
  3. # this model expects a certain database layout and its based on the name/login pattern.
  4. class User <ActiveRecord::Base
  5.   has_many :entries
  6.   has_many :comments
  7.  
  8.   :
  9.   :
  10. end

次にこれに対応する記述をEntryモデルとCommentモデルにも記述します。

RUBY:
  1. class Entry <ActiveRecord::Base
  2.   belongs_to :user
  3. end

RUBY:
  1. class Comment <ActiveRecord::Base
  2.   belongs_to :user
  3. end

これで各モデルに対して、

RUBY:
  1. @user.entries <<@entry
  2. @user.comments <<@comment
  3. @entry.user = @user
  4. @comment.user = @user

のように関連を付けることができます。それでは早速コントローラ側でこの関連づけの設定をしてみましょう。

app/controllers/entries_controller.rb内のcreateアクションとupdateアクションで、それぞれ以下の3行目の定義を加えます。

RUBY:
  1. def create
  2.     @entry = Entry.new(params[:entry])
  3.     @entry.user = @session[:user]
  4.     if @entry.save
  5.       flash[:notice] = 'Entry was successfully created.'
  6.       redirect_to :action => 'list'
  7.     else
  8.       render :action => 'new'
  9.     end
  10.   end

RUBY:
  1. def update
  2.     @entry = Entry.find(params[:id])
  3.     @entry.user = @session[:user]
  4.     if @entry.update_attributes(params[:entry])
  5.       flash[:notice] = 'Entry was successfully updated.'
  6.       redirect_to :action => 'show', :id => @entry
  7.     else
  8.       render :action => 'edit'
  9.     end
  10.   end

これでUserとEntryの関連づけができるようになりました。同様にEntryとCommentの関連付けもしてやれば、一通りの骨組みはできあがり。(かな?)

ということで、練習はこんなものでおしまいにしますか。


About this entry