我有一个导入功能,可让我的用户使用CSV文件导入数据。它有效,但我想让他们的user_id归因于他们导入的数据
这是代码,导入功能:
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为5的数据时,则不会。我想在用CSV导入数据时归因于用户ID,但我不知道该怎么做。
答案 0 :(得分:2)
Product.create!
未使用控制器中定义的def create
。 Read this有待进一步说明。
我会将current_user
从被调用的地方传递到def self.import
。然后将user
分配给您正在创建的新product
对象。因此,假设您将user
传递给def self.import
方法,它将类似于:
product = Product.new(product_hash)
product.user = user
product.save
答案 1 :(得分: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_user
传递给import
这是我不喜欢您的方法的主要原因。 (叫我老式)我喜欢把它们分开。 (对设计模式进行一些调查)。
干杯
答案 2 :(得分:0)
控制器:
def import
Product.import(params[:file], current_user)
redirect_to contacts_url, notice: 'Contact was successfully imported.'
end
型号:
def self.import(file, user)
CSV.foreach(file.path, headers:true) do |row|
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash
product.user = user
product.save!
end