【问题标题】:Rails3-jquery-autocomplete distinct valuesRails3-jquery-自动完成不同的值
【发布时间】:2011-02-11 19:14:31
【问题描述】:

我在具有非唯一值的字段上使用rails3-jquery-autocomplete gem,但我希望它检索到的结果没有重复。关于如何实现这一点的任何想法?

【问题讨论】:

    标签: ruby-on-rails jquery-ui ruby-on-rails-3 jquery-ui-autocomplete


    【解决方案1】:

    我在我的项目https://github.com/marciomr/Terra-Livre 中遇到了同样的问题,我通过以下方式解决了它:

    1. 我将 rails3-jquery-autocomplete 作为插件安装在 vendor/plugin 目录中
    2. 我像这样更改了文件 helpers.rb:
    
    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

    【讨论】:

      【解决方案2】:

      由于我自己遇到了这个问题,我想我会为后代记录自己的解决方案,因为它不需要编辑 gem 的源代码。这是官方维护的 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 编码器(由您选择)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-27
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 2011-06-19
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多