Ruby on rails 检查是否从字符串数组中设置了字段
在我当前的rails项目中,我想根据配置的研究方法加载一些“源”。对于用户配置要使用的方法的研究,此信息在控制器中作为字符串数组提供。另一方面,还有由管理员配置的源,对于我们所说的每个源,源都是有用的 以下是资料来源:Ruby on rails 检查是否从字符串数组中设置了字段,ruby-on-rails,ruby,Ruby On Rails,Ruby,在我当前的rails项目中,我想根据配置的研究方法加载一些“源”。对于用户配置要使用的方法的研究,此信息在控制器中作为字符串数组提供。另一方面,还有由管理员配置的源,对于我们所说的每个源,源都是有用的 以下是资料来源: # == Schema Information # # Table name: sources # # id :integer not null, primary key # title :string(255) #
# == 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"]
@categories@categories=[“网络搜索”、“采访”]
我想做的是类似于“Source.where(@categories=?)”的事情,只获取带有@categories数组中包含的名称的源。对于给定的结构(希望我理解正确),您要做的是基于名称生成搜索
对于您的示例,您需要作为结果获得
.where(WebSearch: true, Interview: true)
从
因此,您需要做的就是将数组映射到这样一个散列中:
Hash[@categories.map{|v|[v, true]}]
最好将其与范围
相结合
class Source < ActiveRecord::Base
scope :with_categories, ->(categories) { where(Hash[categories.map{|v|[v, true]}]) }
end
这将是一种疾病还是一种状况?如果某个类别在列中有一个真实值,这意味着可以吗?@emaillenin的观点很好,如果强制要求未包含在
@category
中的列必须为false,那么我的答案必须略有不同。类别的数量将来会增加还是将始终为4(从几个月以来)只有这四个类别。当未来会出现更多类别时,我将采用更动态的方法进行重构。
class Source < ActiveRecord::Base
scope :with_categories, ->(categories) { where(Hash[categories.map{|v|[v, true]}]) }
end
Source.with_categories(@categories)
Source.joins(:research_categories)
.where("research_categories.name in (:names)", names: @categories)