Rails: Finding all associated objects to a parent object

坚强是说给别人听的谎言 提交于 2020-01-02 10:28:29

问题


I have created a complex object in rails with a principle parent object "Resume" it has a number of child objects for each section("objective_section", "contact_section", etc), is there a way I can fetch all associated objects to the parent object Resume?


回答1:


If by fetch you mean load from the database all in one query, then sure:

Resume.first(:include => [:objective_sections, :contact_sections]) # etc...

If this is a common pattern and you want to DRY things up without much effort, you can throw this into a named_scope in your model:

class Resume < ActiveRecord::Base
  has_many :objective_sections
  has_many :contact_sections

  named_scope :with_sections, :include => [:objective_sections, :contact_sections]
end



回答2:


If your model looks like this:

class Resume < ActiveRecord::Base
  has_many :sections
end

Then you would fetch all the sections for an instance of a Resume with this:

@resume = Resume.find(x)
sections = @resume.sections


来源:https://stackoverflow.com/questions/3740724/rails-finding-all-associated-objects-to-a-parent-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!