检查是否从字符串数组中设置字段

时间:2014-02-09 10:37:48

标签: ruby-on-rails ruby

在我目前的rails项目中,我想加载一些“来源”,具体取决于配置的研究方法。对于研究,用户配置他想要使用的方法,这些信息在控制器中作为字符串数组提供。另一方面,管理员为我们所说的每个来源配置了一些来源,对于这些来源,研究来源是有用的。

这些来源:

# == Schema Information
#
# Table name: sources
#
#  id             :integer          not null, primary key
#  title          :string(255)
#  url            :string(255)
#  WebSearch      :boolean
#  DatabaseSearch :boolean
#  LibrarySearch  :boolean
#  Interview      :boolean

@sources = Source.all

对于布尔字段,存在具有该名称的相应模型。在控制器中,我以这种方式读取激活的方法:

@categories << @question.research_categories.detect{|c| c == params[:type]}

=> @categories = ["WebSearch", "Interview"]

我想做的是像“Source.where(@categories =?)”这样的东西,只获取@categories数组中包含名称的来源。

2 个答案:

答案 0 :(得分:1)

使用给定结构(希望我理解正确)你想要做的是根据名称生成搜索。

根据您的示例,您需要获得

.where(WebSearch: true, Interview: true)

@categories = ["WebSearch", "Interview"]

所以你需要做的就是将数组映射到这样的哈希:

Hash[@categories.map{|v|[v, true]}]

最好将其与scope结合使用。

class Source < ActiveRecord::Base
  scope :with_categories, ->(categories) { where(Hash[categories.map{|v|[v, true]}]) }
end

应该工作(未经测试)并允许你写:

Source.with_categories(@categories)

答案 1 :(得分:0)

Source.joins(:research_categories)
      .where("research_categories.name in (:names)", names: @categories)