2012-05-05 21 views
0

我有一個使用jQuery Tokeninput的「自動完成」字段。基本的查詢,它只是看起來其名稱或用戶名輸入的文本相匹配的用戶,方法是:如何在Rails中使用JQuery Tokeninput自動完成編寫此查詢?

#users_controller.rb 
def index 
    @users = User.where("LOWER(name) like ? OR LOWER(username) like ?", "%#{params[:q].downcase}%", "%#{params[:q].downcase}%").order('name ASC').limit(10) if params[:q] 

    respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @users, :only => [:id, :name, :username] } 

end 

這行之有效

我的應用程序還有一個「追隨者模型」,我想限制哪些用戶出現在自動填充字段中,以便只返回「相互追隨者」。一個「互惠追隨者」是我追隨我的人([A跟隨B]和(B跟隨A)]。

我在用戶模式,返回倒數追隨者用戶的方法:

#user.rb 
# Users relation to Relationships 
has_many :relationships, :foreign_key => "follower_id", :dependent => :destroy 
has_many :followed_users, :through => :relationships, :source => :followed 
has_many :reverse_relationships, :foreign_key => "followed_id", 
           :class_name => "Relationship", 
           :dependent => :destroy 
has_many :followers, :through => :reverse_relationships, :source => :follower 

def reciprocal_followers 
    self.followers & self.followed_users 
end 

我可以得到相互的追隨者鍵入文本的人:

@reciprocal_followers = current_user.reciprocal_followers 

但我怎麼根據輸入的文字列出這些內容?如何將現有的自動完成(@users = User.where ...)查詢與@reciprocal_followers集成?

英語:「我希望自動完成顯示最多10個互惠用戶的列表,其名稱或用戶名與用戶在自動填充字段中輸入的內容類似」。

如何根據「@reciprocal followers」修改定義「@users」限制的查詢?

回答

0

這裏是我結束了工作了:

@users = current_user.reciprocal_followers.select {|u| u.name.downcase =~ /#{params[:q].downcase}/ || u.username.downcase =~ /#{params[:q].downcase}/}.sort_by { |u| [u.name, u.username] }.first(10) if params[:q] 

一位朋友也建議我動了這一點users_controller.rb,進入relationships_controller.rb在那裏我有「跟隨」和「取消關注」的行動,因爲我」我真的在尋找一個恰好是用戶的關係列表(而不只是想要返回用戶)。如果我將它放在users_controller.rb中,我應該將其移出「索引」操作。