我有这样的模型:
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
a)shortened_id
和 b)中。id
fortune
to_json 可以吗?
到目前为止,我有以下内容,这给了我新的 cookie:
user.to_json :methods => :new_cookies
但我一直在试图弄清楚如何在 cookie 对象中包含方法返回的值shortened_id
和 cookie 的id
.