Friday, 15 April 2011

Ruby on Rails - Active Record - Relationships - Many to Many -



Ruby on Rails - Active Record - Relationships - Many to Many -

short version:

this works when team.tournaments not when tournaments.teams. gives me:

<main>'irb(main):117:0> tournament.teams << team (0.1ms) begin transaction (0.0ms) commit transaction team load (0.2ms) select "teams".* "teams" "teams"."tournament_id" = 1 activerecord::statementinvalid: sqlite3::sqlexception: no such column: teams.tournament_id: select "teams".* "teams" "teams"."tournament_id" = 1 long version:

i want have relationship between team , tournament many many relationship. understand have through bring together table done in first portion shown below. there, have add together association shown in team / tournament models respectively.

class teamtournamentjoinattempt3 < activerecord::migration def create_table :teams_tournaments, :id => false |t| t.integer "tournament_id" t.integer "team_id" end add_index :teams_tournaments, ["tournament_id", "team_id"] end def downwards drop_table :teams_tournaments end end

tournament model:

class tournament < activerecord::base has_and_belongs_to_many :teams end

teams model:

class team < activerecord::base has_and_belongs_to_many :tournaments end

now can locate team , tournament in rails console using:

tournament = tournaments.find(1) team = teams.find(1)

then can create relationship between 2 using:

team.tournaments << tournament (0.1ms) begin transaction (0.3ms) insert "teams_tournaments" ("team_id", "tournament_id") values (1, 1) (123.1ms) commit transaction

and boom, think working. when seek go other way (tournament.teams << team) doesn't work giving me next error:

tournament.teams << team (0.1ms) begin transaction (0.0ms) commit transaction team load (0.2ms) select "teams".* "teams" "teams"."tournament_id" = 1 activerecord::statementinvalid: sqlite3::sqlexception: no such column: teams.tournament_id: select "teams".* "teams" "teams"."tournament_id" = 1

seeing teamtournamentjoinattempt3 bet on not using reload! in ruby console after experimenting belongs_to or has_one association.

ruby-on-rails ruby

No comments:

Post a Comment