2011-02-01 72 views
6

我使用https://github.com/crowdint/rails3-jquery-autocomplete它似乎工作。唯一的問題是可以說我有一個字段在所有帖子標題上執行自動完成,但我希望它只顯示用戶創建的帖子的標題。範圍爲rails3的結果jQuery的自動完成插件

有沒有辦法做這樣的事情?即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 < Admin::BaseController 
    autocomplete :brand, :name, :display_value => :funky_method 
end 
In the example above, you will search by name, but the autocomplete list will display the result of funky_method 

我覺得這可能是用來做什麼,我試圖完成的發生,但我不知道從哪裏開始?

回答

2

您應該覆蓋的方法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

1

即使我沒有親自測試,我認爲正常範圍方法在rails3應該工作。由於畢竟範圍也是一個方法一樣「funky_method」

在模型

範圍寫範圍

:funky_method,拉姆達{|參數1 | :條件=> {:柱=參數1} }

,並在控制器

自動完成:品牌:名:DISPLAY_VALUE =>:funky_method

應該工作,試試看..

歡呼

sameera

+0

嗨Sameera,我想: 範圍:funky_method,拉姆達{ 其中( 「post.user_id樣?」,current_user.id) } 但它似乎沒有工作...? – Elliot 2011-02-01 12:13:02

+0

不幸的是,我無法讓範圍適合這顆寶石。我不得不直接修改get_autocomplete_method。好消息是,您可以使用Rails的選擇器查詢或直接SQL來修改get_autocomplete_items方法。在這個例子中,我正在尋找名字和姓氏的匹配。 https://gist.github.com/bb3b54f2ec793cf00fd0 – slant 2011-03-14 00:23:17

7

您可以覆蓋get_autocomplete_items,但第一次使用超級調用get_autocomplete_items方法,然後通過篩選結果current_user.id(或post.user.id如果是郵局的所有者不是當前用戶)

def get_autocomplete_items(parameters) 
    items = super(parameters) 
    items = items.where(:user_id => current_user.id) 
    end 

這樣,您仍然可以使用該寶石的所有其他選項。順便說一句,這應該在你的控制器中完成。

另一個答案建議:scope選項。我研究過這種情況,但在這種情況下不是這樣,你不想在模型中添加「current_user」之類的東西。