问题
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