2010-08-30 51 views
9

我現在弄混淆了,我不知道怎麼刪除/摧毀一個連接表中的記錄:在rails中,如何銷燬'連接表項'而不刪除真實記錄?


class Task < ActiveRecord::Base 
    belongs_to :schema 
    belongs_to :to_do 
end 

class Todo < ActiveRecord::Base 
    belongs_to :schema 
    has_many :tasks 
end 

class Shcema < AcitveRecord::Base 
    has_many :todos 
    has_many :tasks, :through => :todos 
end 

>> sc = Schema.new 
>> sc.tasks << Task.new 
>> sc.tasks << Task.new 
>> sc.tasks << Task.new 
... 
>> sc.tasks.delete(Task.first) # I just want to delete/destroy the join item here. 
# But that deleted/destroyed the Task.first. 

我能做些什麼,如果我只是想要銷燬關係項目?

回答

6

如果要刪除所有任務SC:

sc.tasks.delete_all 

如果你想在SC來刪除一個特定的任務:

sc.tasks.delete_at(x) where x is the index of the task 

or 

sc.tasks.delete(Task.find(x)) where x is the id of Task 

我希望幫助。

1

如果你想刪除連接表像amenities_lodgings所有記錄,而無需使用任何對象,你可以使用:

ActiveRecord::Base.connection.execute("DELETE from amenities_lodgings") 
相關問題