2011-03-11 42 views
2
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 

上述指定车型,我想通过接触控制器采用JSON格式响应代码工作正常,直到我被访问,直到公司的下方指定的命令。想在我的嵌套嵌套的JSON格式响应属性的Rails

@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 

但是现在我想要在我的联系人控制器中嵌套公司的JSON嵌套。所以金德尔在这方面帮助我。 感谢

+0

for activerecord我只会写':include => {:companies =>:phones}' – mpapis 2011-03-11 20:03:31

回答

2

当我对这样的问题的工作,我最后往往覆盖serializable_hash

它产生的JSON和XML时所使用的方法。你只需构建散列来包含任何你想要的。我经常添加我想要的东西,然后将它传递给原来的东西。另外,这样你就不必在控制器中考虑它。你总是可以返回它,而对象将做正确的事情。

def serializable_hash(options = {}) 
    # TODO exclude the id 
    options = {:include => [:address], 
     :except => [:created_at, :updated_at, :creating_user_id]}.merge(options ||= {}) 
    super options 
    end