【发布时间】:2012-11-28 00:12:57
【问题描述】:
我有这样的模型:
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 返回的值。
【问题讨论】:
标签: ruby-on-rails ruby json activerecord