问题描述
我使用rails 3.0.3
I use rails 3.0.3
javascript自动完成需要这样的数据
A javascript auto complete needs data like this
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
我的动作是
def autocomplete
@query = params[:query]
@customers = Customer.where('firstname like ?', "%#{@query}%")
render :partial => "customers/autocomplete.json"
end
我的观点是
{
query:'<%= @query %>',
suggestions: <%= raw @customers.map{|c| "#{c.firstname} #{c.lastname}" } %>,
data: <%= raw @customers.to_json %>
}
它返回
{
query:'e',
suggestions: ["customer 1", "customer 2"],
data: [1, 3]
}
它不起作用,因为建议/数据的数据应该在简单的引号之间...
it's not working because the data for suggestions/data should be between simple quote...
我不能使用to_json方法,因为它将返回对象的所有内容.
I cannot use the to_json method, because it'll returns all the content of my object.
有什么建议吗?
欢呼
推荐答案
注意:这已经过时了, Jbuilder 到目前为止是一个更好的选择.
Note: this is way out of date, Jbuilder is by far a better option.
有两种方法可以解决此问题.如果只需要对象中字段的子集,则可以使用:only
或:except
排除不需要的内容.
There are two ways you can approach this. If you simply need a subset of the fields in an object, you can use :only
or :except
to exclude what you don't want.
@customer.to_json(:only => [:id, :name])
在您的示例中,
看起来您需要以特定格式返回json,因此仅对结果数组进行序列化是行不通的.创建自定义json响应的最简单方法是使用Hash
对象:
in your example it looks like you need to return json in a specific format, so simply serializing an array of results won't work. The easiest way to create a custom json response is with the Hash
object:
render :json => {
:query => 'e',
:suggestions => @customers.collect(&:name),
:data => @customers.collect(&:id)
}
我已经尝试过使用局部函数来构建json响应,但这远不及简单地使用Hash
来实现.
I've tried using partials to build json responses, but that doesn't work nearly as well as simply using Hash
to do it.
将名字和姓氏格式化为单个字符串是您在视图中可能会做的很多事情,我建议将其移动到函数中:
Formatting the first and last names as a single string is something you are likely to do a lot in your views, I would recommend moving that to a function:
class Customer < ActiveRecord::Base
...
def name
"#{first_name} #{last_name}"
end
def name=(n)
first_name, last_name = n.split(' ', 2)
end
end
只有一些便利功能可以使您的生活更轻松,并且控制器/视图更整洁.
Just some convenience functions that makes your life a little easier, and your controllers/views cleaner.
这篇关于输出带Rails 3的格式化json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!