Remove from many-to-many relationship


#1

I have a has_and_belongs_to_many relationship between Tournament and
Team.

How can I remove a team from a tournament without deleting the team
itself, e.g something along these lines.:

tou = Tournament.find(:first)
tou.remove_team(:id => 1)

Thanks,
Dennis


#2

davosian wrote:

I have a has_and_belongs_to_many relationship between Tournament and
Team.

How can I remove a team from a tournament without deleting the team
itself, e.g something along these lines.:

tou = Tournament.find(:first)
tou.remove_team(:id => 1)

Thanks,
Dennis

Tournament.find(:first).teams.delete_if {|team| team.id == 1}

sprinkle error checking to taste…

ilan


#3

t = Team.new :name => “olympic”
=> #<Team:0x31ea6c4 @new_record=true, @attributes={“name”=>“olympic”}

t.save
=> true

tour = Tournament.new :name => “World Cup”
=> #<Tournament:0x31d28bc @new_record=true,
@attributes={“name”=>“World Cup”}

tour.save
=> true

t.tournaments
=> [#<Tournament:0x31ca1d0 @attributes={“team_id”=>“1”, “name”=>“World
Cup”, “id”=>“1”, “tournament_id”=>“1”}, readonlytrue]

t.tournaments.size
=> 1

t.tournaments.delete(tour)
=> [#<Tournament:0x31d28bc @new_record_before_save=true,
@errors=#<ActiveRecord::Errors:0x31ce9c4 @errors={},
@base=#<Tournament:0x31d28bc …>, new_recordfalse,
attributes{“name”=>“World Cup”, “id”=>1}]

This will delete the record in the association table that connects the
team to the tournament.

class CreateTeams < ActiveRecord::Migration
def self.up
create_table :teams do |t|
t.column :name, :string
end

create_table :teams_tournaments do |t|
  t.column :team_id, :integer
  t.column :tournament_id, :integer
end

end

def self.down
drop_table :teams
end
end

class Tournament < ActiveRecord::Base
has_and_belongs_to_many :teams
end

class Team < ActiveRecord::Base
has_and_belongs_to_many :tournaments
end

class CreateTournaments < ActiveRecord::Migration
def self.up
create_table :tournaments do |t|
t.column :name, :string
end
end

def self.down
drop_table :tournaments
end
end

I manually created the record in the join table to create the
relationship between the team and the tournament before I fired up the
script/console session.

So, you have to pass the tournament object not the id when you delete.
For more on this check out :
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000645