カテゴリとタグのリレーション設定

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'
end


Item側では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のところの条件でカテゴリとタグを分けます。


20 May, 2008 | Foodyn ( 実装メモ ) | | Andy
« Prev item - Next Item »
---------------------------------------------

Comments


No comments yet. You can be the first!


Leave comment

© 2007 yoursite.com | Designed by DesignsByDarren
Ported to Nucleus CMS: Suvoroff