[英]In rails, how to destroy a 'join table item' with out deleting the real record?
我現在很困惑,我不知道如何刪除/銷毀連接表中的記錄:
class Task < ActiveRecord::Base
belongs_to :schema
belongs_to :to_do
end
class Todo < ActiveRecord::Base
belongs_to :schema
has_many :tasks
end
class Schema < ActiveRecord::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.
如果我只想銷毀關系項,我該怎么辦?
如果要刪除 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
我希望這有幫助。
如果您想在不使用任何對象的情況下從連接表中刪除所有記錄,如amenities_lodgings
_ amenities_lodgings
,您可以使用:
ActiveRecord::Base.connection.execute("DELETE from amenities_lodgings")
如果要刪除所有連接記錄,可以使用.clear
:
>> sc = Schema.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks << Task.new
>> sc.tasks.size #=> 3
>> sc.tasks.clear
>> sc.tasks.size #=> 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.