Answer the question
In order to leave comments, you need to log in
Rails 5 has many through associations - why does Could not find table 'team_users' error occur?
When I create a migration with the new function in Rails 5, create_join_table, and make a has many through association on the two tables users and teams, for some reason I get the error Could not find table 'team_users'
Migration
rails g migration CreateJoinTableTeamUser team user
class CreateJoinTableTeamUser < ActiveRecord::Migration[5.0]
def change
create_join_table :teams, :users do |t|
t.index [:team_id, :user_id]
t.index [:user_id, :team_id]
end
end
end
class Team < ApplicationRecord
has_many :team_user
has_many :users, through: :team_user
end
class User < ApplicationRecord
has_many :team_user
has_many :teams, through: :team_user
end
class TeamUser < ApplicationRecord
include Userstampable::Stampable
belongs_to :user
belongs_to :team
# validates :user_id, presence: true
# validates :team_id, presence: true
end
2.3.1 :001 > team = Team.first
...
2.3.1 :002 > me = User.first
...
2.3.1 :003 > team.users << me
...
ActiveRecord::StatementInvalid: Could not find table 'team_users'
Answer the question
In order to leave comments, you need to log in
You have it like this:
class CreateJoinTableTeamUser < ActiveRecord::Migration[5.0]
def change
create_join_table :teams, :users do |t|
t.index [:team_id, :user_id]
t.index [:user_id, :team_id]
end
end
end
class CreateTeamUser < ActiveRecord::Migration[5.0]
def change
create_table :team_users do |t|
t.integer team_id
t.integer user_id
end
end
end
rails g migration CreateTeamUsers team_id:integer user_id:integer
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question