In rails, how to destroy a 'join table item' with out deleting the real record?
I get confuse now, I 开发者_StackOverflow社区don't know how to delete/destroy a record in a join table:
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.
What can I do if I just want to destroy the relation item?
If you want to delete all tasks in sc:
sc.tasks.delete_all
If you want to delete a specific task in 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
I hope that helps.
If you want to delete all records from join table like amenities_lodgings
without using any object you can use:
ActiveRecord::Base.connection.execute("DELETE from amenities_lodgings")
Delete All Join Records
If you want to delete all the join records, you can use .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
精彩评论