【发布时间】:2012-04-16 23:01:29
【问题描述】:
我正在尝试在 Rails 应用程序上设置自动完成文本字段。我的问题涉及自定义数据源。
我是这样获取数据的: 我使用this example查找联系人姓名、ID 并添加一个类别以在自动完成中显示它
如果用户是朋友,则分类为联系人,否则分类为其他
@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.to_json
var data = [["AL Tohtori",279,"others"],["Abat Karine",296,"others"]]
与
@result.map {|r| {:label => r[0], :value => r[1], :category => r[2] } }
我好像也买不到。
有什么建议吗?
谢谢!
【问题讨论】:
标签: jquery ruby-on-rails arrays json autocomplete