2014-02-23 46 views
0

我有一個模型項目has_many遊覽。模型關聯has_and_belongs_to_many刪除對象?

class Project < ActiveRecord::Base 
    has_many :excursions 

    def remove_user_from_excursion(excursion_id, current_user) 
     excursions.find(excursion_id).users.delete(current_user) 
     save! 
    end 
end 

然後我有一個模型的遊覽has_and_belongs_to_many_users用戶。

class Excursion < ActiveRecord::Base 
    belongs_to :project 
    has_and_belongs_to_many :users 
end 

我想提供的功能,從遊覽刪除一個用戶,我試圖呼籲項目模型remove_user_from_excursion方法,它似乎並沒有工作。用戶仍然是短途旅行的一部分。我究竟做錯了什麼?

+0

你想刪除用戶和遊覽 –

+0

保存用戶之間或關係!這裏不必要。顯示我們提供的數據庫查詢 –

+0

@AnilMaurya我想刪除用戶和Excursion之間的關係。 –

回答

0

首先,你不能在數組上使用「查找」。在你的情況下,你應該有一個遊覽數組,你想通過id找到它,這將不會這樣工作。 「find」方法適用於模型類,如「Excursion.find(excursion_id)」。

其次,你必須有「工程」的一個實例,以獲取與項目相關的短途旅行,所以你應該使用「自我」 - >「self.excursions ......

最終,做你願意,你可以寫的東西像什麼followig:

def remove_user_from_excursion(excursion_id, current_user) 
    Excursion.find(excursion_id).users.delete(current_user) 
end 

def remove_user_from_excursion(excursion_id, current_user) 
    self.excursions.select{|p| p.id==excursion_id}.first.users.delete(current_user) 
end 

課程的第一選擇是非常非常好:)

0

excursion_instance.users.find(<user_id>).destroy應該做的工作。在這種關係銷燬手段中,銷燬關聯兩個實體的連接表中的記錄,在這種情況下,表ExcursionsUsers。試一試。

+0

你確定你的代碼是刪除關係而不是用戶本身? –

+0

Yeap,當關系是'through'時發生,即您的短途遊覽中有許多用戶通過ExcursionsUsers。試一試控制檯,看看會發生什麼。 – nicooga

+0

'.find().destroy'將查找並加載用戶,並且將銷燬用戶而不是關係。 –

0

下應該工作

def remove_user_from_excursion(excursion_id, current_user) 
    excursions.find(excursion_id).users.destroy(current_user) 
end 
相關問題