开发者

Want to respond in json format of my Nested Nested attribute Rails

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

For above specified models i want respond with JSON format through contact controller the code was working fine until i was accessing till companies the below specified command.

@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

But now i want json of nested Phone element of company in my contact controller. So kinldy help me in this regard. Thanks


When I work on this kind of problem, I often end up overriding serializable_hash

It's the method that's used when generating json and xml. You just build up the hash to contain whatever you want. I often add what I want then pass it to the original. Plus, this way you never have to think about it in the controller. You can always just return it, and the object will do the right thing.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜