I am importing a CSV, that has two columns name and boro.

When I run the import in development, it works fine. But when I do it in production on Heroku, I am getting this error:

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]: 

This is my models/neighborhood, or the lines mentioned in the error rather:

  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  

This is my controllers/neighborhood#import:

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

This is the association between both models:

Neighborhood belongs_to :boro Boro has_many :neighborhoods

This is the schema for 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

This is the schema for Boro:

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

Thoughts?

有帮助吗?

解决方案

So it seems the issue I was having was something to do with the having both :boro, :boro_id in the attributes accessible and the way I was updating that attribute.

Once I got rid of :boro in my attr_accessible list:

attr_accessible :name, :listing_ids, :boro_id

Once I changed that, and didn't try to use update_attributes (which I was doing also) then the above code works fine.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top