【问题标题】:Modifying a method and using params in Rails3在 Rails3 中修改方法和使用参数
【发布时间】:2011-02-10 11:03:21
【问题描述】:

最近我开始使用https://github.com/crowdint/rails3-jquery-autocomplete

效果很好,但我试图为我正在自动完成的结果设置一个范围,在这个问题中我得到了一个很好的答案:Scoping the results for rails3 jquery autocomplete plugin

使用 Claudio 的代码,我已经成功地确定了范围:

class PostsController < ApplicationController
    autocomplete :post, :title

    def get_items(parameters)
        Post.where(:user_id => current_user.id)
    end

这是因为我覆盖了插件的 get_items 方法。你可以在这里看到:https://github.com/crowdint/rails3-jquery-autocomplete/commit/b3c18ac92ced2932ac6e9d17237343b512d2144d#L1R84(我在这次提交之前有一个版本,所以 get_items 仍然适用于我)。

我的范围的问题是自动完成功能不再起作用。当该人开始输入时,get_items 中指定的列表只会弹出,而不是从该列表中建议的项目。

我假设我的覆盖方法有问题。有什么想法吗?

最好, 艾略特

【问题讨论】:

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


    【解决方案1】:

    您刚刚让我意识到,覆盖 get_items 并没有应有的灵活。

    您的代码缺少使用参数[:terms]

    这样的事情应该可以使它工作:

    def get_items(parameters)
      Post.where(:user_id => current_user.id).where(['title LIKE ?', "#{parameters[:term]}%"]
    end
    

    这完全不友好,我会尝试做一些更有意义的事情

    或者,自动完成声明的 :scope 选项可能更有意义?

    【讨论】:

    • 谢谢dabit!我一回到家就试试这个!
    【解决方案2】:

    如果您有多个字段的自动完成功能怎么办?例如,假设您要将其应用于标题和作者。您将如何重写以下内容,使其可以同时服务于两者?

    自动完成 :note, :title, :full => true 自动完成 :note, :author, :full => true

    def get_items(参数) Note.select("distinct title").where(["title LIKE ?", "#{parameters[:term]}%"]) 结束

    目前仅适用于标题字段。它会终止作者字段的自动完成功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      相关资源
      最近更新 更多