0

我有一个名为 Materials 的表,我创建了一个搜索表单。在表单中,我希望选择包含搜索选项名称的框。因此,例如,如果您想按主题搜索,我想要一个包含每个主题之一的下拉菜单。我有这个工作的代码:

@subject = Material.unscoped.select(:subject).where("materials.subject IS NOT NULL
and materials.subject != '' ").uniq

这给了我我想要的以下表单助手:

<%= select_tag "subject", options_from_collection_for_select(@subject, "subject", 
"subject"), :include_blank => true, :class => "input_field" %>

但是 - 我现在只想从共享的材料中选择那些主题。因此,我使用以下方法选择了共享材料:

@shared = Material.where(:status => 'shared')

然后运行这段代码:

@subject = @shared.unscoped.select(:subject).where("@shared.subject IS NOT NULL
and @shared.subject != '' ").uniq

这是行不通的。我认为这是因为 sql 代码无法理解 @shared 对象。但是如何做到这一点?

笔记:

我尝试使用:

@subject = @shared.uniq.pluck(:subject).reject! { |s| s.empty? }

这给出了一个正确字段的数组,但是这不适用于 options_from_collection_for_select。

4

2 回答 2

1

试试这个

@subject = Material.unscoped.select(:subject).where("subject IS NOT NULL and materials.subject != '' and status = 'shared'").uniq 
于 2013-07-29T12:28:06.497 回答
1

shared您可以像这样为查询 创建范围:

scope :shared, where(:status => 'shared')

然后您可以ActiveRecord根据自己的喜好链接方法:

@subject = Material.select(:subject).where("materials.subject IS NOT NULL 
  AND materials.subject != '' ").shared.uniq

更多关于范围的信息:http: //guides.rubyonrails.org/active_record_querying.html#scopes

于 2013-07-29T12:28:33.847 回答