我在具有非唯一值的字段上使用rails3-jquery-autocomplete gem,但我希望它检索的结果是无重复的。关于如何实现这一目标的任何想法?
答案 0 :(得分:1)
我的项目https://github.com/marciomr/Terra-Livre中遇到了同样的问题,我解决了以下问题:
def json_for_autocomplete(items, method, extra_data)
json = items.collect do |item| # here I put the result in a variable
hash = {"label" => item.send(method), "value" => item.send(method)} #here I removed the id
extra_data.each do |datum|
hash[datum] = item.send(datum)
end if extra_data
hash
end
json.uniq # this line is new
end
我从json文件中删除了id,然后检索了uniq值。 因为我不需要id它对我来说很好。我想如果我需要id,我可以把它放在extra_data中,但我不确定。
我刚刚用这个改动分叉了这个项目:git://github.com/marciomr/rails3-jquery-autocomplete.git
答案 1 :(得分:1)
由于我自己遇到了这个,我以为我会为后代录制我自己的解决方案,因为它不需要编辑gem的来源。这是为正式维护的宝石分叉:https://github.com/bigtunacan/rails-jquery-autocomplete。
您可以通过控制器中的自动完成块直接处理json编码,我们可以利用它来更改记录数组。
以下是我们获得学生所在学校的唯一列表的示例:
autocomplete :student, :school do |items|
ActiveSupport::JSON.encode( items.uniq{ |i| i["value"] } )
end
“items”是一个哈希数组,默认情况下包含id,标签和值,因此这只会将唯一值传递给json编码器(您选择的)。