只有在多次出现在数据库中时才从种子中选择

时间:2018-03-14 17:04:14

标签: ruby-on-rails ruby

我有一个TargetMarket类,已经与世界上所有国家/地区一起播种了

TargetMarket.create([
 {name: 'Andorra'},
 {name: 'United Arab Emirates'},
 {name: 'Afghanistan'},
 {name: 'Antigua and Barbuda'},
 ....
 ....
 {name: 'South Africa'},
 {name: 'Zambia'},
 {name: 'Zimbabwe'}
])

然后,用户可以选择他们希望拥有的最多5个国家作为其公司的目标市场。

在公共搜索页面上,我有一个所有TargetMarkets的下拉列表选项。

当前代码读为

<%= f.select :target_markets_id_in, TargetMarket.all.map{ |u| u.name, u.id] }, { include_blank: "All" }, {class: 'selectize-this', multiple: true} %>

然而,这显然显示了所有国家。我只希望被公司用作目标市场的国家填充下拉列表。

例如;一家公司的目标市场是&#34;爱尔兰&#34;,&#34;比利时&#34;,&#34;澳大利亚&#34;和&#34;日本&#34;。

在target_markets搜索选项中,我只希望爱尔兰,比利时,澳大利亚和日本作为可能的搜索选项出现,因为它们是数据库中使用的唯一国家/地区。

这可能吗?

这样的东西
<%= f.select target_market_ids_in, TargetMarkets.where('name' count >= 1) %> 

编辑#

关系

class Company < ApplicationRecord
 has_and_belongs_to_many :target_markets
 accepts_nested_attributes_for :target_markets, allow_destroy: true
end 

2 个答案:

答案 0 :(得分:1)

JOINING和DISTINCTing将为您提供具有关联的唯一对象列表。这是因为默认的Rails'ActiveRecord joinINNER JOIN,它会过滤关联的存在。 ActiveRecord仍然只包含原始表中的SELECT列,因此DISTINCT将返回唯一的对象列表。

在您的情况下,您需要向TargetMarket添加habtm关联(如果它尚不存在):

class TargetMarket < ApplicationRecord
  has_and_belongs_to_many :companies
end

然后替换这一行:

TargetMarket.all.map{ |u| u.name, u.id] }

使用:

TargetMarket.joins(:companies).distinct.map { |u| [u.name, u.id] }

当你在这里时,你可能想看看

的结果
TargetMarket.joins(:companies).distinct.to_sql

答案 1 :(得分:0)

当用户选择他们希望作为公司目标市场的最多5个国家时,您是否将该选择存储为公司与目标市场之间的关联?如果您这样做,那么您只能返回与当前公司相关的目标市场

class Company < ActiveRecord::Base
    has_many :target_markets
end

添加目标市场

@company.target_markets << TargetMarkets.find_by_name('Finland')

显示目标市场

# assuming `@company` is set based on the route (`/company/:id`), `current_user` settings, or however you determine what the current company is
<%= f.select :target_markets_id_in, @company.target_markets.map{ |u| u.name, u.id] }, { include_blank: "All" }, {class: 'selectize-this', multiple: true} %>

进一步阅读