2015-07-21 29 views
0

我有一個導入功能,可讓我的用戶使用CSV文件導入數據。它的工作原理,但我希望有自己的USER_ID歸因於數據他們進口從導入csv函數歸屬當前用戶會話的用戶標識

下面是代碼,導入功能:

def self.import(file) 
CSV.foreach(file.path, headers: true) do |row| 

    product_hash = row.to_hash 
    Product.create!(product_hash) 

end # end CSV.foreach 

來自控制器的product.create:

def create 
    @product = Product.new(product_params) 
    @product.set_user!(current_user) 
    @product.user_id = current_user.id 
    @product.save 
    respond_with(@product) 
end 

當用戶手動創建數據時,這會將用戶標識賦予數據,但當用戶通過導入功能使用CSV創建數據時,不會生成該數據。我想在使用CSV導入數據時將用戶標識歸屬,但我不知道如何去做。

+0

''current_user.id'是您想要根據您的'create'方法分配給每個產品的唯一id,對嗎?所以所有的產品都會有相同的'user_id'正確的? –

+0

如果說人A用100個產品上傳文件,我想讓這100個產品有他的user_id(來自人A的id)。如果人B做同樣的事情,我希望他的user_id歸功於產品(來自人B的id) – dogg

回答

1

Product.create!未使用控制器中定義的def createRead this作進一步解釋。

我會通過current_userdef self.import從任何地方被調用。然後將該user分配給您正在創建的新對象product。因此,假設你通過userdef self.import方法,這將是這樣的:

product = Product.new(product_hash) product.user = user product.save

1

好吧,我個人不喜歡你的方法,我可以在這裏看到它未來的缺陷然而在這種情況下我的建議是保持乾爽並實現你所需要的東西。

在你的模型:

attr_accessor :product_user 

def save_with_a_user 
set_user!(product_user) 
user_id = product_user.id 
save! 
end 

在你的控制器現在你可以說

def create 
    ..... 
    @product.product_user = current_user 
    @product.save_with_a_user 
    ..... 
end 

現在在場景的另一面:

def self.import(file, current_user) 
    CSV.foreach(file.path, headers: true) do |row| 

     product_hash = row.to_hash 
     @product = Product.new(product_hash) 
     @product.product_user = current_user 
     @product.save_with_a_user 

    end # end CSV.foreach 
    end 

你必須重構這個

我一遍又一遍地定義了實例變量(即使重寫它,也不是一個好主意)。另外我還沒有測試過這個。請使用此作爲指導。

不幸的是,你必須通過current_userimport這是我不喜歡你的方法的主要原因。 (叫我老式)我喜歡讓他們分開。 (對設計模式進行一些調查)。

乾杯

+0

我同意你@Mr H關於將'current_user'傳遞給'import' – dewdrops

+1

代碼在你看到' current_user'在這裏和那裏的模型中開始彈出。我自己對此感到愧疚。要知道你有一個很臭的代碼的簡單方法,試着爲模型中的'current_user'進行單元測試。這是一個痛苦的脖子。歡呼聲 –

+0

你好,謝謝你的幫助!我嘗試了你的方法,並用你的方法修改了當前的用戶方法,當我手動添加一個新值時,它運行良好。但是,當我嘗試使用CSV上傳時,出現以下錯誤:未定義的局部變量或方法'current_user'爲#並且它指向導入函數 – dogg