使用Profile.all中的Rails字段填充JSON文件

时间:2011-09-29 04:12:24

标签: jquery ruby-on-rails json jquery-tokeninput

我在我的Rails应用程序中为tags使用jQuery Tokeninput。我以前从未处理过JSON(我是编程新手)但是我想知道是否有一种方法可以创建然后使用Profile.all的字符串值填充json文件。

以下是index中的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

如果有可能,有人可以告诉我如何做到这一点吗?如果需要更多代码,请告诉我!

说明:我想这样做的原因是将@tags限制为已存在的代码。

1 个答案:

答案 0 :(得分:0)

那么,如果我理解正确,您发布的代码是否正常工作?但是现在您不想将JSON输出流式传输到浏览器,而是将其写入文件?

看看Rails如何在the source中呈现JSON。它非常简单,它只是在正在渲染的任何对象上调用to_json函数。

还要看看Yehuda Katz的this excellent post。查找序列化部分。

现在,要将所有Profile模型作为JSON保存到文件中,您可以执行以下操作:

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

修改

根据您添加的说明,这里有更多信息:

模型中某些字段的JSON:

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

这将在Ruby中为您提供这样的数组:

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

和JSON一样:

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