繁体   English   中英

Ruby on Rails / Active Record查询:如果字段/具有数组的记录不包含元素,则返回

[英]Ruby on rails / Active Record Query: return if field / record with array not contains element

我在TravelIdeas表中输入了country_trips字段,其中包含国家/地区数组。

#<TravelIdea:0x007faa7bec40f0> {
                      :id => 9,
                :idea_key => "romantic",
               :idea_type => nil,
                    :cost => 2000,
              :created_at => Mon, 10 Jul 2017 07:48:49 UTC +00:00,
              :updated_at => Mon, 16 Oct 2017 08:10:47 UTC +00:00,
           :country_trips => [
                [0] "PL"
               ],
     :available_languages => [
                [0] "pl"
              ]
}

本地旅行在:country_trips中为nil,所以我可以忽略它们:

idea.where.not(country_trips: nil) if country.present?

我有我的用户目的地国家,所以我想向他展示所有包含他梦his以求的旅行想法。

就像SQL Server CONTAINS(列,“国家”)一样

可能这与LIKE无关,因为这与将1个国家匹配到1个国家无关。

例如country = user.destination_country表示: country = "PL"

:country_trips => [
   [0] "PL",
   [1] "DE"
   ],

我正在寻找某事

TravelIdea.where(country_trips: country)

会返回在country_trips数组中包含该国家/地区的所有旅行想法:P

这是一个更多的postgres问题,第8.15.5 在数组中搜索说:

SELECT * FROM sal_emp WHERE 10000 = ANY (pay_by_quarter);

就您而言,您可以将其写为.where方法中的SQL段:

TravelIdea.where("? = ANY (country_trips)", country)


[英]#<ActiveRecord::AssociationRelation Active Record Query Ruby on Rails

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM