2012-04-03 17 views
0

私は、レールアプリケーションにオートコンプリートテキストフィールドを作成しようとしています。私の問題は、カスタマイズされたデータソースに関係しています。オートコンプリートjqueryのためにレールにjson形式の配列を渡します。

ここで私は、データを取得する方法は次のとおりです。ユーザーが友人の場合、カテゴリはそれ以外の連絡先、である、私は連絡先名を探し IDとthis example

を使用してオートコンプリートでそれを表示するカテゴリを追加カテゴリは他のものです

@result = Array.new 
# find the current user id when its viewed as a contact 
@current_contact = Contact.find_by_user_id(current_user).id 
#go through all the contacts 
Contact.order('name ASC').each do |a| 
    #if the current contact is a friend of the user 
    if Relationship.find_by_user_id_and_contact_id(current_user, a) 
    #add it to the array with the 'contacts' category 
    @result << [a.name, a.id, 'contacts'] 
    else 
    #if its not a friend, and its not himself, add it to the array with the 'others' category 
    unless @current_contact == a.id 
     @result << [a.name.to_s,a.id, 'others'] 
    end 
    end 
end 

この形式を出力すると、オートコンプリート機能でデータソースとして使用できるようになりますか?

の例では、私はJSON形式

var data = [ 
{ label: "andreas andersson", category: "People" }, 
{ label: "andreas johnson", category: "People" } 
]; 

あるように思われ、探しています。しかし、私はその一つに私の出力を変換することができないようなフォーマットを示しています。私は

@result.map {|r| {:label => r[0], :value => r[1], :category => r[2] } } 

@result.to_json 

VARデータ= [[" AL Tohtori "、279、"他人"]、["アバトカリーヌ"、296、"他人"]]

を試してみました

私はそれも持っていないようです。

提案がありますか?

ありがとうございます!

答えて

0

あなたはアプローチを組み合わせてみてください:

@result.map {|r| {:label => r[0], :value => r[1], :category => r[2] } }.to_json 

それはそれは、JBuilderのようなJSONビューライブラリを使用するのが最適かもしれません解決しない場合。それについての良いスクリーンキャストがありますhere

関連する問題