2013-02-13 63 views
0

我正在導入一個CSV文件,它有兩列nameboroActiveRecord :: AssociationTypeMismatch on CSV導入

當我在開發中運行導入時,它工作正常。但是,當我這樣做是在生產在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 

這是米堡的模式:

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

的思考?

回答

0

所以看來我遇到的問題與:boro, :boro_id中的屬性可訪問性和我更新該屬性的方式有關。

一旦我在我的attr_accessible名單擺脫:boro

attr_accessible :name, :listing_ids, :boro_id 

有一次,我改變了這一切,並沒有嘗試使用update_attributes(我也做),那麼上面的代碼工作正常。

相關問題