Rails 4 CSV Import and setting a value to a key value

前端 未结 1 614
夕颜
夕颜 2021-01-06 19:04

I\'m a complete Rails n00b and i\'m sure this is an easy thing to do but i\'m having trouble. I would like to take the value of a key in my URL and set it to the :category_i

相关标签:
1条回答
  • 2021-01-06 19:11

    if the class method import is called in the import controller action, you can pass params[:category_id] as the 2nd parameter.

    class ManufacturersController < ApplicationController
      def import
        Manufacturer.import(params[:file], params[:category_id])
      end
    end
    
    class Manufacturer < ActiveRecord::Base
      def self.import(file, category_id)
        CSV.foreach(file.path, headers: true) do |row|
          record = Manufacturer.where(
            :category_id => category_id,
            :name => row[0]
          ).first_or_create
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题