简体   繁体   English

Rails:组合实例变量,以显示具有不同值的唯一记录

[英]Rails: Combining Instance Variable, to display unique record with distinct values

I'm combining two instance variables, but its displaying two of the same values because sometimes each of my instance variable has the same record. 我正在合并两个实例变量,但是它显示两个相同的值,因为有时我的每个实例变量都具有相同的记录。 How do I only display distinct? 我如何只显示与众不同?

  @var1 = Image.tagged_with(params[:tags])
  @var2 = Image.psql_search(params[:tags])

  @Combined = @var1 + @var2

@var1 is from acts-as-taggable gem, and @var2 is from postgresql full-text. @ var1来自acts-as-taggable gem,@ var2来自postgresql全文。

Get the unique IDs of the objects and map them to a new array (using OpenStruct in place of ActiveRecord objects here for example): 获取对象的唯一ID并将它们映射到新数组(例如,在这里使用OpenStruct代替ActiveRecord对象):

@combined = [OpenStruct.new(:id => 1), OpenStruct.new(:id => 1), OpenStruct.new(:id => 2)]
#=> [#<OpenStruct id=1>, #<OpenStruct id=1>, #<OpenStruct id=2>]
@combined.map(&:id).uniq.map {|x| @combined.find {|y| y.id == x}}
#=> [#<OpenStruct id=1>, #<OpenStruct id=2>]

This solution doesn't address original database queries, and only addresses presentation issues. 此解决方案不解决原始数据库查询,仅解决表示问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM