Rails 5 有很多关联 - 找不到 table 'team_users'
Rails 5 has many through associations - Could not find table 'team_users'
我在Rails5中生成jointable迁移时,出现错误
迁移
rails g migration CreateJoinTableTeamUser team user
20161011185253_create_join_table_team_user.rb
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]
t.timestamps null: false, include_deleted_at: true
t.userstamps index: true, include_deleter_id: true
end
end
end
team.rb
class Team < ApplicationRecord
has_many :team_user
has_many :users, through: :team_user
end
user.rb
class User < ApplicationRecord
has_many :team_user
has_many :teams, through: :team_user
end
团队_user.rb
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'
我认为您正在尝试创建一个 table,因此最好使用 'model' 生成器而不是迁移,因为理想情况下应该使用迁移来更新现有的 table 模式。
尝试以下操作:
rails g model team_user user:references team:references
然后
rails db:migrate
希望对你有帮助。
我在Rails5中生成jointable迁移时,出现错误
迁移
rails g migration CreateJoinTableTeamUser team user
20161011185253_create_join_table_team_user.rb
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]
t.timestamps null: false, include_deleted_at: true
t.userstamps index: true, include_deleter_id: true
end
end
end
team.rb
class Team < ApplicationRecord
has_many :team_user
has_many :users, through: :team_user
end
user.rb
class User < ApplicationRecord
has_many :team_user
has_many :teams, through: :team_user
end
团队_user.rb
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'
我认为您正在尝试创建一个 table,因此最好使用 'model' 生成器而不是迁移,因为理想情况下应该使用迁移来更新现有的 table 模式。
尝试以下操作:
rails g model team_user user:references team:references
然后
rails db:migrate
希望对你有帮助。