2017-02-18 31 views
1

我想在rails中創建自加入。自加入使用postgresql的rails 5.0中

class ItemGroup < ApplicationRecord 
    has_many :children, class_name: "ItemGroup", foreign_key: "parent_id" 

    belongs_to :parent, class_name: "ItemGroup" 
end 

這是我的代碼,但是當我嘗試添加新記錄時,它並不保存它。那麼這個代碼中的問題是什麼,任何人都可以幫助我,或者給我一些關於自我加入的想法。

class CreateItemGroups < ActiveRecord::Migration[5.0] 
    def change 
    create_table :item_groups do |t| 
     t.string :name 
     t.integer :parent_id 
     t.text :description 
     t.references :parent, index: true 

     t.timestamps 
    end 
    end 
end 

這是我的移民文件。

回答

2

Rails 5使得默認情況下需要關聯belongs_to。要禁用它,你需要添加optional: truebelongs_to

belongs_to :parent, class_name: "ItemGroup", optional: true 
+0

謝謝...它的工作...所以你能告訴我如何訪問數據也 –

+0

​​<%= f.parent.name%>我試圖使用這個,但它沒有給我提供名稱 –

+0

這裏f是一個循環參數 –