class Contact < ActiveRecord::Base
has_many :contact_company_profiles, :dependent => :destroy
accepts_nested_attributes_for :contact_company_profiles, :allow_destroy => true
has_many :companies, :through => :contact_company_profiles
has_many :phones, :as => :phoneable, :dependent => :destroy
accepts_nested_attributes_for :phones
end
class ContactCompanyProfile < ActiveRecord::Base
belongs_to :contact
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :contact_company_profiles
has_many :contacts, :through => :contact_company_profiles
has_many :phones, :as => :phoneable, :dependent => :destroy
end
对于上面指定的模型,我想通过联系人 Controller 以 JSON 格式响应代码工作正常,直到我访问公司以下指定的命令。
@contacts = Contact.find(:id)
respond_to do |format|
format.html
format.js
format.json { render :json=>@contacts.to_json(:include=>[:companies, :phones) }
format.xml { render :xml => @contacts }
end
但现在我想在我的联系人 Controller 中包含公司的嵌套电话元素的 json。所以kinldy在这方面帮助我。 谢谢
最佳答案
当我处理这类问题时,我经常以覆盖 serializable_hash 而告终
就是生成json和xml时使用的方法。您只需构建哈希以包含您想要的任何内容。我经常添加我想要的内容,然后将其传递给原始内容。另外,这样您就不必在 Controller 中考虑它。您可以随时返回它,该对象将做正确的事情。
def serializable_hash(options = {})
# TODO exclude the id
options = {:include => [:address],
:except => [:created_at, :updated_at, :creating_user_id]}.merge(options ||= {})
super options
end
关于ruby-on-rails - 想要以我的嵌套嵌套属性 Rails 的 json 格式响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5272685/