0
我有一個InventoryItem模型如下:find_or_initialize_by非唯一屬性
class InventoryItem < ActiveRecord::Base
belongs_to :item, :foreign_key => :code, :primary_key => :code
belongs_to :vendor
has_many :list_items
has_many :shopping_lists, through: :list_items
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
InventoryItem.create! row.to_hash
end
end
end
我想修改self.import方法,這樣我可以上傳CSV文件,它會find_or_initialize。通過這種方式,我可以更新庫存,而不必刪除它,並在每次價格變化時重新填充它。我的問題是,我無法找到主要的:id
屬性,因爲傳入的CSV文件不知道這些ID。這裏是我的InventoryItem表模式:
class InventoryItems < ActiveRecord::Migration
def change
create_table :inventory_items do |t|
t.decimal :price
t.integer :vendor_id
t.integer :code, :limit => 8
end
add_index :inventory_items, [:code, :vendor_id]
end
end
:code
不是唯一的,因爲許多其他廠商具有相同的代碼相同的產品。有沒有辦法find_or_initialize_by代碼和vendor_id?你有沒有看到我想要做的其他解決方法?任何幫助深表感謝。提前致謝!
編輯
好了,所以我有一個現在看起來像這樣的方法:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
my_object = InventoryItem.find_or_initialize_by_code_and_vendor_id(code, vendor_id)
my_object.update_attributes(row.to_hash)
end
end
但我怎麼通過在每個代碼和VENDOR_ID到find_or_initialize_by?
沒關係啊高興地看到,這是相當簡單的。謝謝。但有一個問題,當來自CSV文件的時候,我如何將每個'code'和'vendor_id'傳遞給find_or_initialize方法?我會用我的修改方法更新我的問題。 – settheline
假設你知道這些字段中的每一個字段將在哪個列中執行'InventoryItem.find_or_initialize_by_code_and_vendor_id(row [0],row [1])' –
因此,你應該指定行而不是列? – settheline