2011-02-07 11 views
10

私は現在、親/子関係を処理するための標準的な1対1の関係を使用しています:Railsの - 親/子関係

class Category < ActiveRecord::Base 
    has_one :category 
    belongs_to :category 
end 

はそれを行うための推奨方法はありますかこれは大丈夫でしょうか?

答えて

18

あなたはこの作業を取得するために使用している名前を微調整する必要があります - あなたは関係の名前を指定し、言うクラスが何であるかをAR:関係は対称である

class Category < ActiveRecord::Base 
    has_one :child, :class_name => "Category" 
    belongs_to :parent, :class_name => "Category" 
end 
+0

どのように我々は、特定の親のための子カテゴリを見つけるのですか。 – demonchand

+0

parent.childだけ使用できますか? –

+0

私は実際に私の心が "has_one:parent; belongs_to::children"という同じことをより合理的に配慮していることに気付きました。これは、私にはどんな意味がありませんカテゴリ/親/ 3 /子供/ 1 – slacy

-2

ので、I実際に私は次のことを好むことを、トビーが書いたものよりもそれが異なる見つける:

class Category < ActiveRecord::Base 
    has_one :parent, :class_name => "Category" 
    belongs_to :children, :class_name => "Category" 
end 

私の心の物事の方法である「片親、多くの子どもたちが持っている」、「唯一の子、多くの親を持っている」ではないいくつかの理由

+2

ような何かをしたい場合はルートに記述する必要がありますどのような – LandonSchropp

+0

これは、周りに正確に他の方法が答えになります - Railsの5.1.4を使用> http://stackoverflow.com/a/38791328/473040 – equivalent8

4

has_manyのバージョン:

class Category < ActiveRecord::Base 
    has_many :children, :class_name => "Category" 
    belongs_to :parent, :class_name => "Category" 
end 

#migratio 
class CreateCategories < ActiveRecord::Migration 
def change 
    create_table :categories do |t| 
     t.integer :parent_id 
     t.string :title 

     t.timestamps null: false 
    end 
end 
end 

# RSpec test 
require 'rails_helper' 
RSpec.describe Category do 
    describe '#parent & #children' do 
    it 'should be able to do parent tree' do 
     c1 = Category.new.save! 
     c2 = Category.new(parent: c1).save! 

     expect(c1.children).to include(c2) 
     expect(c2.parent).to eq c1 
    end 
    end 
end 
+0

を。私は私が上記のc2.parentに従うと、c1.childは私にエラーを与えることがわかりました:ActiveRecord :: StatementInvalid(Mysql2 :: Error:Unknown column 'categories.category_id' in 'where clause':SELECT 'categories 。* FROM 'categories' WHERE' categories'.category_id' = 5 – guero64

+0

'has_many:children、:class_name =>" Category "、foreign_key:" id "' – equivalent8

0
私はそれがRailsの5のために動作させるために、@ equivalent8のソリューションへの軽微な変更をしなければならなかったことがわかった

(5.1.4):

class Category < ActiveRecord::Base 
    has_many :children, :class_name => "Category", foreign_key: 'parent_id' 
    belongs_to :parent, :class_name => "Category", foreign_key: 'parent_id', :optional => true 
end 

foreign_key宣言なしRailsはparent_idとchokesの代わりにorganization_idで子を見つけようとします。

また、belongs_toからbelongs_toアソシエーション上の:optional => true宣言のないチョークも、Rails 5ではデフォルトでインスタンスが割り当てられる必要があります。この場合、無制限の数の親を割り当てる必要があります。