Idriss
Idriss

Reputation: 102

rails change boolean value within a loop

Hi everyone I need help with this method: I have a method that loops trough two models' data and compare them; if a match is found, I want to set the nih_pub match attribute to true then return all nih_pub that have match as false. it woks well if I use the commented if statement if nih.pubyear == "2003" and nih.pmid == "12538806", but it is not working with the looping.

below is the method i am using:

def compare
  nih_pub = NihPublication.where(user: current_user).all
  pubmed_pub = Publication.where(user: current_user).all

  nih_pub.each{ |nih|
    pubmed_pub.each {|pubmed|
      if nih.pubyear == pubmed.publication_year and  nih.pmid == pubmed.pubmed_id
      # if nih.pubyear == "2003" and  nih.pmid == "12538806"
        nih.match = true
        nih.save!
      end
    }
  }

  @missing = nih_pub.where(match: false)
end

Thank for your help

Upvotes: 0

Views: 378

Answers (1)

Chris Peters
Chris Peters

Reputation: 18090

This is likely a data type issue. You can compare data types in your console like this:

def compare
  nih_pub = NihPublication.where(user: current_user).all
  pubmed_pub = Publication.where(user: current_user).all

  nih_pub.each{ |nih|
    pubmed_pub.each { |pubmed|
      puts "nih.pubyear #{nih.pubyear.class.name}" 
      puts "pubmed.publication_year #{pubmed.publication_year.class.name}"
      puts "nih.pmid #{nih.pmid.class.name}"
      puts "pubmed.pubmed_id #{pubmed.pubmed_id.class.name}"

      if nih.pubyear == pubmed.publication_year and nih.pmid == pubmed.pubmed_id
      # if nih.pubyear == "2003" and  nih.pmid == "12538806"
        nih.match = true
        nih.save!
      end
    }
  }

  @missing = nih_pub.where(match: false)
end

If you see something like this:

nih.pubyear Integer
pubmed.publication_year String
nih.pmid Integer
pubmed.pubmed_id String

Then you know that you'll need to cast values when comparing them.

I suspect that you'll need to change your code to something like this (though this is only a guess and is based on the debug output I have listed above):

def compare
  nih_pub = NihPublication.where(user: current_user).all
  pubmed_pub = Publication.where(user: current_user).all

  nih_pub.each{ |nih|
    pubmed_pub.each { |pubmed|
      # Cast those strings to integers so you're comparing apples to apples.
      if nih.pubyear == pubmed.publication_year.to_i and nih.pmid == pubmed.pubmed_id.to_i
        nih.match = true
        nih.save!
      end
    }
  }

  @missing = nih_pub.where(match: false)
end

Upvotes: 1

Related Questions