开发者

Rails: Finding all associated objects to a parent object

开发者 https://www.devze.com 2023-01-16 21:09 出处:网络
I have created a complex object in rails w开发者_如何学Cith a principle parent object \"Resume\" it has a number of child objects for each section(\"objective_section\", \"contact_section\", etc), is

I have created a complex object in rails w开发者_如何学Cith 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?


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


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
0

精彩评论

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