【发布时间】:2017-05-11 14:19:59
【问题描述】:
我在运行rake db:seed 时收到错误ActiveRecord::RecordInvalid: Validation failed: Team must exist。
我正在尝试在玩家和团队之间建立关联。我有数据要播种到我的数据库中,但我不确定错误是由我如何设置关联或我如何构建数据引起的。
Team 是父级,Player 是子级。
型号
# player.rb
class Player < ApplicationRecord
belongs_to :team, class_name: "Player"
validates :team, presence: true, allow_nil: true
end
# team.rb
class Team < ApplicationRecord
has_many :players
end
路线
# routes.rb
Rails.application.routes.draw do
get 'welcome/index'
resources :players
resources :teams do
resources :players
end
root 'welcome#index'
end
迁移
# create_players.rb
class CreatePlayers < ActiveRecord::Migration[5.1]
def change
create_table :players do |t|
t.belongs_to :team, index: true
t.string :name
t.string :shoots
t.string :catches
t.string :position
t.string :pos
t.integer :number
t.integer :gp
t.integer :goals
t.integer :assists
t.integer :points
t.integer :pim
t.integer :plusMinus
t.decimal :gaa
t.integer :svs
t.integer :team_id
t.references :teams
t.timestamps
end
end
end
# create_teams.rb
class CreateTeams < ActiveRecord::Migration[5.1]
def change
create_table :teams do |t|
t.string :team_name
t.string :abr
t.string :sm_logo
t.string :lg_logo
t.integer :player_id
t.timestamps
end
end
end
尝试播种的数据示例
# Player data
players = Player.create!({
"name": "Some Guy",
"shoots": "Right",
"position": "Forward",
"pos": "F",
"number": 8,
"gp": 15,
"goals": 12,
"assists": 6,
"points": 18,
"pim": 12,
"plusMinus": 7,
"team_id": 1
})
# Team data
teams = Team.create!({
"team_name": "A Team",
"abr": "ATM"
})
宝石文件
source 'https://rubygems.org'
gem 'rails', '~> 5.1.0'
gem 'pg', '~> 0.18'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
#Bootstrap 4 and Tether gems
gem 'bootstrap', '~> 4.0.0.alpha6'
gem 'rails-assets-tether', '>= 1.3.3', source: 'https://rails-assets.org'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'rails-ujs', '~> 0.1.0'
gem 'jquery-rails'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console', '>= 3.3.0'
gem 'listen', '>= 3.0.5', '< 3.2'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
【问题讨论】:
标签: postgresql activerecord ruby-on-rails-5