Ruby on rails 如何使用has\u和\u-belies\u-to\u-many关系为数据库种子

Ruby on rails 如何使用has\u和\u-belies\u-to\u-many关系为数据库种子,ruby-on-rails,ruby,activerecord,many-to-many,Ruby On Rails,Ruby,Activerecord,Many To Many,我正在尝试构建一个种子文件,该文件填充一个state、country和zip表。拉链可以存在于多个州和县。县和州包含多个拉链。我的州和县种子工作得很好,但我在播种时遇到了问题。当我使用种子文件而不尝试引用关系时,它可以工作,但当我尝试建立连接时收到一个错误。我假设我只是对多对多关系错误地使用了.create方法 型号 class County < ActiveRecord::Base belongs_to :state has_and_belongs_to_many :zi

我正在尝试构建一个种子文件,该文件填充一个state、country和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
最后,运行“rake db:seed”时出现的错误


ActiveRecord::UnknownAttributeError:unknown属性:state

错误表示您正在尝试设置state属性,而Zip没有该属性。Zip有一个名为states的集合。我想你应该说:

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

也许可以看看这个答案:
Zip.create(code: code, states: [ State.find(5) ])