首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails在循环中更改布尔值。

rails在循环中更改布尔值。
EN

Stack Overflow用户
提问于 2016-05-11 18:35:57
回答 1查看 331关注 0票数 0

大家好,我需要这个方法的帮助:我有一个循环两个模型的数据并比较它们的方法;如果找到匹配,我希望将 nih_pub match属性设置为true,然后返回所有匹配为false的nih_pub。如果我使用注释的if语句if nih.pubyear == "2003" and nih.pmid == "12538806",它工作得很好,但是它不适用于循环。

下面是我使用的方法:

代码语言:javascript
复制
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

谢谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-11 18:52:04

这可能是一个数据类型问题。您可以像这样比较控制台中的数据类型:

代码语言:javascript
复制
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

如果你看到这样的事情:

代码语言:javascript
复制
nih.pubyear Integer
pubmed.publication_year String
nih.pmid Integer
pubmed.pubmed_id String

然后,您就会知道,在比较它们时,您需要转换值。

我怀疑您需要将代码更改为类似的内容(尽管这只是猜测,并且基于我上面列出的调试输出):

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37170791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档