Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In rails, how to destroy a 'join table item' with out deleting the real record?

I get confuse now, I 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?

like image 548
Croplio Avatar asked Aug 30 '10 23:08

Croplio


1 Answers

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
like image 88
Joshua Pinter Avatar answered Sep 28 '22 07:09

Joshua Pinter