开发者

Populate a JSON file with Rails fields in Profile.all

I'm using jQuery Tokeninput for tags in my Rails app. I have never dealt with JSON before (I'm new to programming) but I was wondering if there was a way to create then populate a json file with string values from Profile.all.

Here is the index in my TagsController:

class TagsController < ApplicationController
  def index
    @tags = Tag.where("name like ?", "%#{params[:q]}%")
    respond_to do |format|
      format.html
      format.json { render :json => @tags.map(&:attributes) }
 开发者_开发知识库   end
  end
end

If it is possible, can someone give me an idea of how it might be done? If more code is needed let me know!

EXPLANATION: The reason I want to do this is to limit @tags to tags that already exist.


So, if I understand correctly, the code you posted works correctly? But now you don't want to stream the JSON output to the browser, but write it to a file?

Take a look at how Rails renders JSON in the source. It's pretty straightforward, it simply calls the to_json function on any object that is being rendered.

Also take a look at this excellent post by Yehuda Katz. Look up the section for Serialization.

Now, to save all your Profile models as JSON to a file, you can do something like this:

File.open("all_profiles.json", "w") { |f| f.write(Profile.all.to_json) }

Edit:

With your added explanation, here's some more info:

JSON of certain fields in your models:

Profile.all.collect { |p| { :name => p.name, :city => p.city } }.to_json

This would give you an array like this in Ruby:

[ {:name = "John", :city => "Liverpool"}, {:name = "Jimi", :city => "Seattle"} ]

And JSON like this:

[ {"name":"John", "city":"Liverpool"}, {"name":"Jimi", "city":"Seattle"} ]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜