ruby-on-rails – 每个循环中带有“或”语句的Rails 3.0
发布时间:2020-12-17 02:03:08 所属栏目:百科 来源:网络整理
导读:我正在尝试构建一个比较两个对象的查询,如果它们具有相同的id,则不会获取该记录.我有的是这个: @channels.each do |channel| unless @guide_channels.where(:id = channel.id).exists? @dropdown_channels = @dropdown_channels.where(:id = channel.id) en
我正在尝试构建一个比较两个对象的查询,如果它们具有相同的id,则不会获取该记录.我有的是这个:
@channels.each do |channel| unless @guide_channels.where(:id => channel.id).exists? @dropdown_channels = @dropdown_channels.where(:id => channel.id) end end 这会创建查询,但在每个值之间放置一个AND,这不是我想到的.我想要“或”运算符.是否有一个’orwhere’功能我可以使用或有更好的方法来做一些比较功能? 解决方法
关键是AR :: Relation对象的.where()方法将条件添加到一组条件中,然后在执行查询时将它们一起进行AND编辑.
你需要做的是像NOT IN这样的查询: # select all the ids for related @guide_channels # if @channels comes from a query (so it's a ActiveRecord::Relation): guide_ids = @guide_channels.where(:id => @channels.pluck(:id)).pluck(:id) # use .where(:id => @channels.map {|c| c.id}) instead if @channels is just an array # then use the list to exclude results from the following. @dropdown_channels = @dropdown_channels.where("id NOT IN (?)",guide_ids.to_a) 第一个查询将累积在@guide_channels中具有条目的频道的所有ID.第二个将使用第一个结果从下拉列表的结果中排除找到的通道. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |