2014-08-28 46 views
0

我有一個has_many的問題,我不明白我在哪裏錯了,在這裏搜索並沒有給我一個答案呢。rails has_many給'未定義的方法'/銷燬不會刪除外鍵

我正在寫一個litte應用程序來管理派對。因此,一個對人民幫助在黨

class Person < ActiveRecord::Base 
    has_many :sections 
end 

的一個模型部分來管理不同的地方的模型的人(一個shotbar,一個地方獲得食品等)

class Section < ActiveRecord::Base 
    belongs_to :person 
    has_many :shifts 
end 

的路由用我只是(他們的工作)

resources :people 
resources :sections 

我的遷移情況如下

class CreatePeople < ActiveRecord::Migration 
def change 
create_table :people do |t| 
    t.string :vname 
    t.string :nname 
    t.string :mail 

    t.timestamps 
end 
end 
end 

class CreateSections < ActiveRecord::Migration 
def change 
create_table :sections do |t| 
    t.string :name 
    t.text :text 
    t.integer :person_id 

    t.timestamps 
end 
end 
end 

我的問題是:我所理解的has_many我現在應該能夠使用

@stuff=Person.sections 

獲得其中某個人工作的所有部分。

然而,這給了我「未定義的方法`部分'爲#」。當我摧毀了一個人並且部分對象中的外鍵仍然存在時,實際上發生了問題,而我認爲rails會將它們設置爲NULL,例如,

@person=Person.find(8) 
@person.destroy 

結束了某處

couldn't find person with id=8 

同時取得部

def show 
    @section=Section.find(params[:id]) 
    if @section.person_id 
    @person=Person.find(@section.person_id) 
    end 
end 

的表演動作,我不知道該怎麼做,或者如果我錯過了一些遷移。 Rails似乎並沒有承認這一對多關係。我已經檢查過文檔和東西,但找不到差異。也許你可以幫忙。

非常感謝,斯文

+2

'sections'方法是'Person'實例,而不是類定義的。 – 2014-08-28 12:04:02

+0

謝謝!那解決了第一個問題......但是爲什麼在我摧毀某個人之後仍然存在外鍵?我希望的是,當我從系統中刪除一個人的每個部分person_id,這個人在哪裏工作,被設置爲NULL – Sven 2014-08-28 12:12:32

回答

2

您可以添加相關規則,如:

class Person < ActiveRecord::Base 
    has_many :sections, dependent: :destroy 
    ... 

這會破壞人摧毀前的人的部分。

看起來像你需要:

class Person < ActiveRecord::Base 
    has_many :sections, dependent: :nullify 
+0

謝謝!幫助我很多...不知何故,我忽視了無效選項... – Sven 2014-08-28 12:34:02

相關問題