2017-08-02 120 views
1

我就知道让谁拥有了搜索结果的产品的所有用户的最佳方式获得的搜索产品的用户搜索结果

我控制器

@users = User.all // i must change here ? 
    if params[:product_type].present? && params[:location].present? && params[:discount].present? 
     @products = Product.near(params[:location], 1, units: :km).where(product_type: params[:product_type], discount: params[:discount]) 
    end 

我的观点

<% @products.each do |p| %> 
    <%= p.user.company_name %> 
<% end %> 

我方法的工作,但如果一个公司有2个产品它的显示它2次

+0

可能就像在_p.users.uniq.company_name_上调用_.uniq_一样简单,但需要查看模型和关联以确认。 –

回答

1

假设以下:

User has_many :products 
Product belongs_to :user 

你可以这样做:

@users_from_product_results = User.where(id: @products.pluck(:user_id)) 

如果有几个产品,是指同一个用户,该用户将可以只列出一次。

+0

感谢您的帮助,但我得到SQL错误“子查询有太多列” –

+0

@AntoineWako尝试我更新的答案。另外,您使用的是哪种数据库系统? – MrYoshiji

+0

我使用PostgreSQL –

0

使用includes(eager_loading),可以在单个查询中提供产品和用户,而不是进行2个独立的AR调用。

if params[:product_type].present? && params[:location].present? && params[:discount].present? 
    @products = Product.near(params[:location], 1, units: :km).where(product_type: params[:product_type], discount: params[:discount]) 
.includes(:user) 
end 

并在视图,您可以使用@products.map(:users).uniq这给所有与产品相关的用户。