Forum: Ruby on Rails Remove from many-to-many relationship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
davosian (Guest)
on 2007-03-09 23:09
(Received via mailing list)
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
Ilan B. (Guest)
on 2007-03-10 00:50
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
(Guest)
on 2007-03-10 05:00
(Received via mailing list)
>> 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/As...
This topic is locked and can not be replied to.