Importing CSV data into Rails app, using something other then the association “id”

前端 未结 3 1789
我寻月下人不归
我寻月下人不归 2021-01-06 01:18

I am trying to import a few CSV files into my rails app. I learned and managed to import tables into Models without association.

Now i have managed to import the da

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-06 01:49

    Thank you everyone for the help. Below is what ended up working for me. The biggest issue i was getting was Origin and Destination. There is only one Port table, which includes a list of the Ports. Ports are used for both Origin and Destination.

    class Rate < ApplicationRecord
    
      def self.import(file)
        CSV.foreach(file.path, headers: true) do |row|
          rate = find_by_id(row["id"])
          Rate.create! row.to_hash
        end
      end
    
      belongs_to :origin, :class_name => 'Port'
      belongs_to :destination, :class_name => 'Port'
      belongs_to :carrier
      belongs_to :shipment_category
      belongs_to :unit_of_measure
      has_many :additional_items
    
    # associatiing Origin and Destination Port Code
    def origin_port_code
      origin.try(:port_code)
    end
    
    def origin_port_code=(port_code)
      self.origin = Port.where(:port_code => port_code).first
    end
    
    def destination_port_code
      destination.try(:port_code)
    end
    
    def destination_port_code=(port_code)
      self.destination = Port.where(:port_code => port_code).first
    end
    
    # associating carrier name
      def carrier_name
        carrier_name.try(:name)
        #code
      end
      def carrier_name=(name)
        self.carrier = Carrier.where(:name => name).first
        #code
      end
    
    
    # associating Shipment Category Name
      def shipment_category_name
        shipment_category.try(:name)
      end
    
      def shipment_category_name=(name)
        self.shipment_category = ShipmentCategory.where(:name => name).first
      end
    
    
    
      # associating unit_of_measure name
      def unit_of_measure_name
        unit_of_measure.try(:name)
        #code
      end
      def unit_of_measure_name=(name)
        self.unit_of_measure = UnitOfMeasure.where(:name => name).first
        #code
      end
    
    
    end
    

提交回复
热议问题