【问题标题】:Adding assocation to CSV import from form从表单添加关联到 CSV 导入
【发布时间】:2019-12-30 05:12:54
【问题描述】:

我想在导入时将current_user.id 添加到 CSV 导入的每个字段中。

我已成功导入 CSV 文件,但当我尝试以下操作时:

型号:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    product_hash = row.to_hash
    product = Product.find_or_create_by!(sku: product_hash['sku'])
    product.update_attributes!(product_hash)
  end
end

控制器:

  def create
    user = current_user
    Product.import(params[:product][:file], user_id: user.id)
    respond_to do |format|
      format.html { redirect_to '/', notice: 'Products successfully imported.' }
    end
  end

表格:

<%= form_for @product, url: product_upload_create_path do |f| %>
  <%= f.file_field :file  %>
  <%= f.submit %>
<% end %>

(也尝试为用户添加隐藏字段)

错误:

ArgumentError(参数数量错误(给定 2,预期 1)):

因为我不能调用模型中的 current_user(或者,从我所读到的,这是一个坏主意)。我还能如何将 current_user.id 附加到每个 CSV 导入行?

【问题讨论】:

    标签: ruby-on-rails ruby csv


    【解决方案1】:

    如果您的操作如此简洁,那么模型是一个不错的地方(对于更长的预处理,您可能会选择使用服务,但只有几行,模型就可以了)。

    虽然您无法访问模型中的 current_user(它是视图和控制器可用的辅助操作,因为它依赖于会话)但您几乎可以将其传递给模型,这是完全可以接受的。

    假设您直接上传文件(在某些不允许您接受文件上传的托管解决方案中不可能),那么您的方法将有效,如果您将其更改为允许文件名和用户对象也是。

    我会将模型方法更改为:

    def self.import(file:, user_id:)
      CSV.foreach(file.path, headers: true) do |row|
        product_hash = row.to_hash.merge(user: user_id)
        product = Product.find_or_create_by!(sku: product_hash['sku'])
        product.update_attributes!(product_hash)
      end
    end
    

    并将实现更改为

    Product.import(file: params[:product][:file], user_id: user.id)
    

    仅供参考,def method_name(param:, param_2:) 的符号表示两个参数都是必需的。如果你只需要一个,你可以做def method_name(param:, param_2:nil),这使得第二个参数是可选的

    【讨论】:

    • 任何人遇到这个...product_hash = row.to_hash.merge(user_id: user_id 是我必须做出的一个改变
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多