开发者

Rails 3 - Creating a JSON response to display Search Results

I'm working to have Rails 3 res开发者_如何学JAVApond with a JSON request which will then let the app output the search results with the jQuery template plugin...

For the plugin to work, it needs this type of structure:

[
 { title: "The Red Violin", url: "/adadad/123/ads", desc: "blah yada" },
 { title: "Eyes Wide Shut", url: "/adadad/123/ads", desc: "blah yada" },
 { title: "The Inheritance", url: "/adadad/123/ads", desc: "blah yada" }
]

In my Rails 3 controller, I'm getting the search results which come back as @searchresults, which contain either 0 , 1 , or more objects from the class searched.

My question is how to convert that to the above structure (JSON)...

Thank you!

Update Forgot to mention. The front-end search page will need to work for multiple models which have different db columns. That's why I'd like to learn how to convert that to the above to normalize the results, and send back to the user.


I am not really sure what is the problem here, since you can always call ".to_json" on every instance or collection of instances or hash, etc.

You can use .select to limit the number of fields you need, ie:

Object.select(:title, :url, :desc).to_json

I am guessing that the @searchresults is ActiveRecord::Relation, so you probably can use:

@searchresults.select(:title, :url, :desc).to_json
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜