1:nの自己参照 = 木構造のデータをRailsで扱いたい
具体的には、SetucoCMSのCategoriesテーブル。ERDは↓こんなの
https://spreadsheets.google.com/spreadsheet/pub?hl=ja&hl=ja&key=0AsZ5eShbQ7T_dDJRRm5pdkJUUDlHQUVobnhPckFnWWc&output=html
外部キーの名前も、デフォルトの
migrationの定義
こうした。
1 class CreateCategories < ActiveRecord::Migration 2 def self.up 3 create_table :categories do |t| 4 t.string :name, :null => false 5 t.integer :parent_id 6 t.timestamps 7 end 8 end 9 10 def self.down 11 drop_table :categories 12 end 13 end
Categoryモデルの定義
こうした。
1 # -*- coding:UTF-8 -*- 2 class Category < ActiveRecord::Base 3 has_many :pages 4 5 has_many :children, :class_name => 'Category', :foreign_key => :parent_id 6 belongs_to :parent, :class_name => 'Category', :foreign_key => :parent_id 7 8 end
試す(`・ω・´)
~/programming/ruby/SetucoCMSR$ rails c
Loading development environment (Rails 3.0.7)
ruby-1.9.2-p180 :001 > Category.all
=> []
ruby-1.9.2-p180 :002 > c = Category.create([
ruby-1.9.2-p180 :003 > {:name => 'cat1'},
ruby-1.9.2-p180 :004 > {:name => 'cat2', :parent_id => 1},
ruby-1.9.2-p180 :005 > {:name => 'cat3', :parent_id => 1},
ruby-1.9.2-p180 :006 > {:name => 'cat4', :parent_id => 2}
ruby-1.9.2-p180 :007?> ])
=> (snip)
ruby-1.9.2-p180 :008 > pp c
[#<Category id: 1, name: "cat1", parent_id: nil, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">,
#<Category id: 2, name: "cat2", parent_id: 1, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">,
#<Category id: 3, name: "cat3", parent_id: 1, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">,
#<Category id: 4, name: "cat4", parent_id: 2, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">]
=> (snip)
ruby-1.9.2-p180 :009 > pp c[0].children
[#<Category id: 2, name: "cat2", parent_id: 1, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">,
#<Category id: 3, name: "cat3", parent_id: 1, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">]
=> (snip)
ruby-1.9.2-p180 :010 > pp c[1].parent
#<Category id: 1, name: "cat1", parent_id: nil, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">
=> (snip)
ruby-1.9.2-p180 :011 > pp c[1].children
[#<Category id: 4, name: "cat4", parent_id: 2, created_at: "2011-06-02 10:56:44", updated_at: "2011-06-02 10:56:44">]
=> (snip)
でけた!
0 件のコメント:
コメントを投稿