CSV导入时的ActiveRecord :: AssociationTypeMismatch

时间:2013-02-13 08:01:46

标签: ruby-on-rails csv heroku import csv-import

我正在导入CSV,其中有两列nameboro

当我在开发中运行导入时,它工作正常。但是当我在Heroku上进行制作时,我收到了这个错误:

2013-02-13T07:53:43+00:00 app[web.1]: Started POST "/neighborhoods/import" for xx.xx0.xx.xx at 2013-02-13 07:53:43 +0000
2013-02-13T07:53:43+00:00 app[web.1]: 
2013-02-13T07:53:43+00:00 app[web.1]: ActiveRecord::AssociationTypeMismatch (Boro(#52915220) expected, got String(#18916260)):
2013-02-13T07:53:43+00:00 app[web.1]:   app/models/neighborhood.rb:20:in `block in import'
2013-02-13T07:53:43+00:00 app[web.1]:   app/models/neighborhood.rb:19:in `import'
2013-02-13T07:53:43+00:00 app[web.1]:   app/controllers/neighborhoods_controller.rb:85:in `import'
2013-02-13T07:53:43+00:00 app[web.1]: 
2013-02-13T07:53:43+00:00 app[web.1]: 

这是我的models/neighborhood,或错误中提及的行:

  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      neighborhood = where(name: row["name"]).first_or_create!(row.to_hash.slice(*accessible_attributes))
      boro = Boro.find_by_name(row["boro"])
      neighborhood.boro = boro      
      neighborhood.save!
    end
  end  

这是我的controllers/neighborhood#import

def import
  Neighborhood.import(params[:file])
  redirect_to imports_index_url, notice: "Neighborhoods imported."
end

这是两个模型之间的关联:

Neighborhood belongs_to :boro Boro has_many :neighborhoods

这是邻居的架构:

# Table name: neighborhoods
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  boro_id    :integer

这是Boro的架构:

# Table name: boros
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null

思想?

1 个答案:

答案 0 :(得分:0)

因此,我遇到的问题似乎与可访问属性中的:boro, :boro_id和我更新该属性的方式有关。

我在:boro列表中删除了attr_accessible后:

attr_accessible :name, :listing_ids, :boro_id

一旦我改变了,并且没有尝试使用update_attributes(我也在做),那么上面的代码工作正常。