How to seed a database with a has_and_belongs_to_many relationship
我正在尝试构建一个填充state,县和邮政编码表的种子文件。邮编可以存在于多个state和县。县和state包含多个邮政编码。我的state和县的种子可以正常工作,但是我在给拉链做种子时遇到了问题。当我在不尝试引用该关系的情况下使用种子文件时,它可以工作,但是在尝试建立连接时收到错误消息。我以为我对多对多关系只是错误地使用了.create方法。
型号
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class County < ActiveRecord::Base belongs_to :state has_and_belongs_to_many :zips end class State < ActiveRecord::Base has_many :county has_and_belongs_to_many :zips end class Zip < ActiveRecord::Base has_and_belongs_to_many :counties has_and_belongs_to_many :states end |
迁移
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | class CreateStates < ActiveRecord::Migration def change create_table :states do |t| t.string :name t.string :abbreviation t.timestamps end end end class CreateCounties < ActiveRecord::Migration def change create_table :counties do |t| t.string :name t.references :state, index: true t.timestamps end end end class CreateZips < ActiveRecord::Migration def change create_table :zips do |t| t.string :code t.timestamps end create_table :zips_counties, id: false do |t| t.belongs_to :zip t.belongs_to :county end create_table :zips_states, id: false do |t| t.belongs_to :zip t.belongs_to :state end end end |
种子文件-注意..这不是最终版本,我只是在尝试使包括多对多关系在内的任何工作。 '5'确实存在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | County.delete_all State.delete_all Zip.delete_all ActiveRecord::Base.connection.reset_pk_sequence!('states') ActiveRecord::Base.connection.reset_pk_sequence!('counties') CSV.foreach("lib/tasks/state_table.csv") do |state| name = state[0] abbr = state[1] State.find_or_create_by!(name: name, abbreviation: abbr) end CSV.foreach("lib/tasks/counties.csv") do |county| name = county[0] state = county[1] County.create(name: name, state: State.find_by(abbreviation: state)) end CSV.foreach("lib/tasks/zip_codes.csv") do |zip| code = zip[0] county = zip[1] state = zip[2] #puts state if County.find_by(name: county) != nil && County.find_by(name: county).state.abbreviation == state #puts State.find_by(abbreviation: state).abbreviation == state #puts County.find_by(name: county).state.abbreviation #puts State.find_by(abbreviation: state).id Zip.create(code: code, state: State.find(5)) end end |
最后,当我运行" rake db:seed"时出现错误
ActiveRecord :: UnknownAttributeError:未知属性:状态
该错误表明您正在尝试设置state属性,而Zip没有该属性。邮编有一个称为state的集合。我想你想说:
1 | Zip.create(code: code, states: [ State.find(5) ]) |