我正在尝试构建一个填充州、县和邮政编码表的种子文件。邮政编码可以存在于多个州和县。县和州包含多个邮政编码。我的州和县种子工作正常,但我在播种 zipper 时遇到问题。当我使用种子文件而不尝试引用关系时,它可以工作,但当我尝试建立连接时收到错误。我假设我只是错误地使用 .create 方法来处理多对多关系。
模型
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
迁移
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”确实存在
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:未知属性:状态
最佳答案
该错误表明您正在尝试设置 Zip 没有的状态属性。 Zip 有一个名为 states 的集合。我想你想说的是:
Zip.create(code: code, states: [ State.find(5) ])
关于ruby-on-rails - 如何使用 has_and_belongs_to_many 关系为数据库添加种子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25772752/