如何使用has_and_belongs_to_many关系为数据库设定种子

时间:2014-09-10 18:41:56

标签: ruby-on-rails ruby activerecord many-to-many

我正在尝试构建一个填充州,县和zip表的种子文件。拉链可以存在于多个州和县。县和州包含多个拉链。我的州和县种子工作正常,但我在拉链拉链时遇到问题。当我使用种子文件而不尝试引用该关系时,它可以工作,但是当我尝试建立连接时收到错误。我假设我只是错误地使用.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

种子文件 - 注意..这不是最终版本,我只是想做任何包含多对多关系的工作。 &#39; 5&#39;确实存在

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

最后,我运行时的错误&#34; rake db:seed&#34;

ActiveRecord :: UnknownAttributeError:未知属性:状态

1 个答案:

答案 0 :(得分:1)

错误是抱怨您正在尝试设置Zip没有的state属性。 Zip有一个名为states的集合。我想你想说:

Zip.create(code: code, states: [ State.find(5) ])