Q: removing duplicate entry for csv import in ruby while importing csv row i need to check wether this is duplicate entry or new entry.
my csv looks like this,
         company,location,region,service,price,duration,disabled
         Google,Berlin,EU,Design with HTML/CSS,120,30,false
         Google,San Francisco,US,Design with HTML/CSS,120,30,false
         Google,San Francisco,US,Restful API design,1500,120,false
         Apple,London,EU,Design with HTML/CSS,120,30,false
         Google,Berlin,EU,Design with HTML/CSS,120,30,false
         Google,San Francisco,US,Restful API design,1500,120,false

Also the row value should be imported in different table whose association is like this
A Company:


*

*can have multiple regions: US, EU and each region multiple branches, i.e. London, Berlin. Define a hierarchy to represent this logic.

*has many Services. If there are more branches, they will all share the same services

*can be disabled


A Service:


*

*has a duration

*has a price

*can be disabled

*if the company is disabled, all services are disabled.


for which i have implemented  association like this
       class Company < ApplicationRecord
         has_many :regions
         has_many :services
         has_many :locations, through: :regions
       end

        class Region < ApplicationRecord
         belongs_to :company
           has_many :locations
        end

        class Location < ApplicationRecord
          belongs_to :region
          belongs_to :company
        end

        class Service < ApplicationRecord
          belongs_to :company
         end

How will I import this?
I am doing something like this
  namespace :import do
    desc "Import  data"
    task company:  :environment do

      CSV.foreach('lib/data/companies_data.csv', headers:true) do |row|
        company = Company.create(:name => row["company"])
        region = company.regions.create(:name => row["region"])
        if region.id and company.id
           location = company.locations.create(:name =>row["location"], 
                        :region_id => region.id)
            service = company.services.create(:name => row["service"], 
                      :price => row["price"], :duration => 
                          row["duration"], :disabled =>row["disabled"])
        end
      end
    end
  end

How do I check wether a row is already present in database as it already contains associated table. 

A: You can use .first_or_create. This will only create new db records if there is not a match on the previous ActiveRecord Relation call:
Model.where(some_unique_field: row['Unique Column']).first_or_create(row)
You can also pass a block to first_or_create as listed in the docs if you want to apply any additional logic to the CSV row ie model.price = row['price'] + fee
