0

我正在导入一个 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

这是 Neighborhood 的架构:

# 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

想法?

4

1 回答 1

0

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

一旦我摆脱了:boro我的attr_accessible清单:

attr_accessible :name, :listing_ids, :boro_id

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

于 2013-02-13T10:51:29.930 回答