大家好,我需要这个方法的帮助:我有一个循环两个模型的数据并比较它们的方法;如果找到匹配,我希望将 nih_pub match属性设置为true,然后返回所有匹配为false的nih_pub。如果我使用注释的if语句if nih.pubyear == "2003" and nih.pmid == "12538806",它工作得很好,但是它不适用于循环。
下面是我使用的方法:
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谢谢你的帮助
发布于 2016-05-11 18:52:04
这可能是一个数据类型问题。您可以像这样比较控制台中的数据类型:
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如果你看到这样的事情:
nih.pubyear Integer
pubmed.publication_year String
nih.pmid Integer
pubmed.pubmed_id String然后,您就会知道,在比较它们时,您需要转换值。
我怀疑您需要将代码更改为类似的内容(尽管这只是猜测,并且基于我上面列出的调试输出):
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)
endhttps://stackoverflow.com/questions/37170791
复制相似问题