【问题标题】:to_json, is this possible?to_json,这可能吗?
【发布时间】: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) 中idfortune

to_json 可以做到这一点吗?

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

user.to_json :methods => :new_cookies

但我一直在试图弄清楚如何在 cookie 对象中包含方法 shortened_id 和 cookie 的财富 id 返回的值。

【问题讨论】:

    标签: ruby-on-rails ruby json activerecord


    【解决方案1】:

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

    class User < ActiveRecord::Base
    
      def as_json(options={})
        json_res = super
        json_res['cookies'] = ...
      end
    
    end
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2018-10-21
      • 2014-11-30
      相关资源
      最近更新 更多