2017-10-17 32 views
0

我已经在我的TravelIdeas表字段country_trips中,其中包含国家/地区数组。Ruby on Rails/Active Record Query:如果字段/记录不包含元素,则返回

#<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为零,所以我可以忽略它们:

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

我有我的用户目的地国家,所以我想向他出示所有的旅行理念包含了梦想的国家。

这将是某事像SQL Server包含(列,“国家”)

也许这是不是LIKE,因为这是不是1个国家匹配1个国家。

例如 country = user.destination_country 手段: country = "PL"

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

我在寻找某物像

TravelIdea.where(country_trips: country)

,将返回其拥有这一切旅行的想法计数的国家ry_trips数组:P

+0

难道你使用Rails的''serialize:country_trips',或者你使用RDMS内置系统来存储数组吗? (像这样postgres https://www.postgresql.org/docs/9.1/static/arrays.html) – MrYoshiji

+0

我使用postgres数组 – eudaimonia

+0

试试这个'TravelIdea.where('country_trips = any(?)',' PL')'(你可以谷歌* postgres数组rails *,你会发现像这样的有用信息https://coderwall.com/p/sud9ja/rails-4-the-postgresql-array-data-type) – MrYoshiji

回答

1

这更是一个Postgres的问题,部分8.15.5. Searching in Arrays说:

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

在你的情况,你可以写为.where方法里面SQL段:

TravelIdea.where("? = ANY (country_trips)", country) 
相关问题