to_json,这可能吗?

时间:2012-11-28 00:12:57

标签: ruby-on-rails ruby json activerecord

我有这样的模特:

class User < ActiveRecord::Base
    has_many :cookies
    has_many :fortunes, :through => :cookies

    def new_cookies
        cookies.all :include => :fortune, :conditions => {:opened => false}
    end
end

class Cookie < ActiveRecord::Base
    belongs_to :user
    belongs_to :fortune

    def self.find_by_shortened_id(shortened_id)
        find(shortened_id.alphadecimal)
    end

    def shortened_id
        self.id.alphadecimal
    end
end

class Fortune < ActiveRecord::Base
    serialize :rstatuses
    serialize :genders 

    has_many :cookies
    has_many :users, :through => :cookies
end

我需要将User对象转换为json,但我希望它包含所有cookies with new(通过new_cookies方法),并嵌入cookies a){ {1}}和b)shortened_id的{​​{1}}。

这可以用to_json吗?

到目前为止,我有以下内容给了我新的cookie:

id

但是我一直试图找出如何在cookie对象中包含方法fortune返回的值和cookie的财富user.to_json :methods => :new_cookies

1 个答案:

答案 0 :(得分:0)

您可以在用户模型中覆盖as_json

class User < ActiveRecord::Base

  def as_json(options={})
    json_res = super
    json_res['cookies'] = ...
  end

end

如果应用程序中的多个位置需要这些类型的JSON自定义,您应该查看用于呈现JSON的jbuilder gem