确定rails3 jquery自动完成插件的结果范围
我正在使用https://github.com/crowdint/rails3-jquery-autocomplete ,它似乎正在工作。 唯一的问题是假设我有一个字段在所有post标题上执行自动完成,但我希望它只显示用户创建的post标题。
有没有办法做这样的事情? 即find_by还是什么?
谢谢!
-Elliot
编辑
它在文档中说:
If you want to display a different version of what you're looking for, you can use the :display_value option. This options receives a method name as the parameter, and that method will be called on the instance when displaying the results. class Brand < ActiveRecord::Base def funky_method "#{self.name}.camelize" end end class ProductsController :funky_method end In the example above, you will search by name, but the autocomplete list will display the result of funky_method
我觉得这可以用来做我想要完成的事情,但我不知道从哪里开始?
你应该覆盖方法get_item ,例如在这些情况下我将过滤用户列表考虑到最后一个:
class UsersController < ApplicationController autocomplete :user, :email, :full => true def index @users = User.all end def get_items(parameters) [User.last] end
我认为最后一次提交之一,改变了方法(#get_items)的名称。 检查autocomplete.rb文件的版本。
请在此处查看: https : //github.com/crowdint/rails3-jquery-autocomplete/commit/b3c18ac92ced2932ac6e9d17237343b512d2144d#L1R84 。
您可以覆盖get_autocomplete_items
,但首先使用super来调用原始的 get_autocomplete_items
方法,然后通过current_user.id过滤结果(如果post的所有者不是当前用户,则过滤post.user.id)
def get_autocomplete_items(parameters) items = super(parameters) items = items.where(:user_id => current_user.id) end
这样你仍然可以使用gem附带的所有其他选项。 这应该在您的控制器中完成。
另一个答案建议:scope
选项。 我调查了一下,但在这种情况下不是这样的,你不想在模型中添加“current_user”等类似的东西。
即使我没有亲自测试过,我认为rails3中的正常范围方法应该可行。 因为所有范围也是与“funky_method”相同的方法
写一个范围
在你的模型中
范围:funky_method,lambda {| param1 | :conditions => {:column = param1}}
并在你的控制器
autocomplete:brand,:name,:display_value =>:funky_method
应该工作,试着看看..
干杯
sameera