2016-09-18 17 views
0

我有模型稱爲部分,我希望部分能夠有很多部分 - 所以自我加入似乎是一個開始的地方。Rails - 沒有適當的訪問自我加入模型

設置我這樣的代碼:

型號文件

class Section < ApplicationRecord 
    belongs_to :offer 
    has_many :offer_items 

    # Self joins: 
    has_many :child_sections, class_name: "Section", foreign_key: "parent_id" 
    belongs_to :parent_section, class_name: "Section", optional: true 
end 

遷移文件

class CreateSections < ActiveRecord::Migration[5.0] 
    def change 
    create_table :sections do |t| 
     t.string :name 
     t.references :offer, foreign_key: true 

     t.references :parent_section, foreign_key: true 
     t.timestamps 
    end 
    end 
end 

正如你可以看到我設置belongs_to :parent_section是可選的,因爲沒有每部分應該有它的父母。

當我打印我的第模型attribute_names它說:

=> ["id", "name", "offer_id", "parent_section_id", "created_at", "updated_at"] 

試圖檢索child_sections得到我的錯誤:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: sections.parent_id: SELECT "sections".* FROM "sections" WHERE "sections"."parent_id" = ? 

哪裏我做我的錯誤?

回答

1

你不必在你的sections

改變這個parent_id

has_many :child_sections, class_name: 'Section', foreign_key: 'parent_id' 

在此:

has_many :child_sections, class_name: 'Section', foreign_key: 'parent_section_id' 
+0

所有的小東西。上次我忘了一封信「s」,這一次......謝謝! Dzięki! – Ancinek

+0

不起作用的一件事是如果我想創建一個子節它不會被保存,這是因爲offer_id是零)。手動創建小節時設置offer_id可以解決該問題。有沒有辦法自動實現它? – Ancinek

+0

你可以在''部分''中像'before_create'那樣創建一些回調函數,我也不確定,但是我認爲你可以通過這種方式獲得offer的所有部分: 'something_offer.sections.joins(:child_sections)'。 –