DollarChills
DollarChills

Reputation: 1086

find_or_create_by ignore if column not nil

I have a rake file setup to import JSON data from an external URL. In this JSON there is a field titled 'deleted'. This field is a BIGINT, and if the field has been deleted then it will fill with random BIGINT.

I want to import all rows except those that have the 'deleted' field populated.

This is what I have so far, which works well except importing all rows.

data_json['Agent'].each do |data|
 agent = Agent.find_or_create_by(agent_id: data['id'])
 agent. agent_id = data['id']
 agent.first_name = data['first_name']
 agent.last_name = data['last_name']
 agent.deleted = data['deleted']
 agent.save
end

Upvotes: 0

Views: 235

Answers (1)

DivXZero
DivXZero

Reputation: 611

I believe what you're looking for it the next keyword. You could try something like this:

data_json['Agent'].each do |data|
  agent = Agent.find_or_create_by(agent_id: data['id'])
  agent. agent_id = data['id']
  agent.first_name = data['first_name']
  agent.last_name = data['last_name']
  agent.deleted = !data['deleted'].nil?  # Force this into a bool
  next if agent.deleted?
  agent.save
end

Upvotes: 1

Related Questions