Categories
open all | close allTags
Migration | スキンエンジン | Flash | パソコン | RESTful | 名称 | CSRF | フォーム | OpenID | 国際化 | アクセス制御 | Aptana | タグ | モデル | 認証 | デュアル・コア | Subversion | ドキュメント | テスト | rakeSearch
カテゴリとタグのリレーション設定
Foodynではタグとカテゴリは1テーブルで管理し,どのアイテムがどのカテゴリ,あるいはタグに属しているかを中間テーブルを使って記す方法を取っています。Ruby on Railsではこれはhabtn(has and belongs to many)あるいはhas_many throughという方法で取り扱います。ここでは中間テーブルも明示的にいじれるように後者の実装を採用します。中間テーブルのTagCategoryでは次のように取り扱います。
class TagCategory < ActiveRecord::Base
set_base_name 'tag_category'
belongs_to :categories, :class_name=>'Category', :foreign_key=>'category_id'
belongs_to :items, :class_name=>'Item', :foreign_key=>'item_id'
endItem側ではitemオブジェクトに対してitem.categoriesとすればカテゴリ一覧を,item.tagsとすればタグ一覧を表示するために条件を加えてやります。
has_many :categories, :through => :tag_category, :conditions=>"cleft is not null"
has_many :tags, :through => :tag_category, :source=>:categories, :conditions=>"caliasid is not null"
has_many :tag_category
2行目で:source=>:categoriesとしているのはTagCategoryの belongs_to:categoiesを参照しなさいという意味。
これで :conditionsのところの条件でカテゴリとタグを分けます。
Comments
No comments yet. You can be the first!