2012-11-28 92 views
0

我有模型是这样的:to_json,这可能吗?

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有是新的(通过new_cookies方法),并在这些cookies一)shortened_id嵌入和b)id它的fortune

to_json可能吗?

我有后续到目前为止,给了我新的Cookie:

user.to_json :methods => :new_cookies 

但我被困在试图找出如何在cookie中包括对象的方法shortened_id返回的值与饼干的财富的id

回答

0

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

class User < ActiveRecord::Base 

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

end 

如果需要在应用程序中的几个地方,这些类型的JSON自定义的,你应该有一个看看jbuilder gem渲染你的JSON。