2016-01-21 65 views
0

我有三種模式。客戶,工作和收據。無法刪除Ruby on Rails中的記錄

客戶有很多工作和工作有很多收據。作業屬於客戶,收據屬於作業。

在我的客戶刪除清單中,我想刪除所有的客戶工作和工作收據。這裏是我的控制器代碼

def destroy 
    customer = Customer.find(params[:id]) 
    customer.jobs.receipts.destroy_all #this line crashes 
    customer.jobs.destroy_all 
    customer.destroy 
    redirect_to customers_url 

    redirect_to show_todays_jobs_path 
end 

,說customer.jobs.receipts.destroy_all拋出,指出該收據的方法是未定義的錯誤的行。

但是,在我的作業控制器中,jobs.receipts.destroy_all工作得很好。在客戶控制器中,如果我刪除線來銷燬收據,那麼這也可以正常工作。

我不明白爲什麼我無法刪除客戶控制器中的收據。請幫我在這裏。在此先感謝

+0

能告訴你喬布斯控制器? –

+1

我們需要看到你的模型關係。 –

回答

2

您的代碼中的問題,customer.jobs是一個集合,其中每個工作記錄有自己的收據集合。您可以在客戶模型中使用關聯has_many :receipts, through: :jobs以獲得直接customer.receipts參考,然後您可以撥打customer.receipts.delete_allDocumentation here

看來你可以使用dependent: :destroydependent: :delete_all您協會has_many,簡要當customer對象被銷燬它將刪除關聯。結帳documentation

就以代碼示例來看看:

class Customer 
    has_many :jobs, dependent: :destroy 
end 


class Job 
    has_many :receipts, dependent: :destroy 
end 

然後當你調用customer.destroy所有相關的就業和收入可能被銷燬。

PS。控制器代碼中有另一個錯誤 - redirect_to調用了兩次,只有一次是可能的。

1

您不應該在控制器中手動執行這些刪除操作。您可以向模型中的關聯提供參數,告訴他們在銷燬父項時銷燬相關記錄。

我做了一些假設你的模型關聯,但沿東西線以下爲您應該工作:通過調用

class Customer < ActiveRecord::Base 
    has_many :jobs, dependent: :destroy 
end 

class Job < ActiveRecord::Base 
    belongs_to :customer 
    has_many :receipts, dependent: :destroy 
end 

class Receipt < ActiveRecord::Base 
    belongs_to :job 
end 

對關聯設置dependent: :destroy告訴Rails刪除相關記錄他們的destroy方法刪除父對象時。

有了這個設置,你可以做到這一點在你的destroy動作控制器內(注意有沒有必要,你destroy它之前find您的記錄):

def destroy 
    Customer.destroy(params[:id]) 
    redirect_to customers_url 
end