Desired loading of existing objects

In rails, you can get loading associations when creating a new object as follows:

@person = Person.find(params[:id], :include => {:flights => :plane}) 

However, I sometimes already have an @person object, and then I want it to load associations. It seems that there is no way to "rails". I am looking for something like this basically:

 @person = Person.find(params[:id]) ... @person.include({:flights => :plane}) 

There is a background, I have a before filter, which already creates an @object without associations. But in some actions, if I do not want to load associations, I will create many singular queries. And making

 @person = Person.find(params[:id]) ... @person = Person.find(params[:id], :include => {:flights => :plane}) 

seems a bit unnecessary.

+4
source share
2 answers

In Rails 2, you can use scoped to create the appropriate request:

  @person.flights.scoped(:include => :plane) 

In Rails 3, you can do this Rails 3 Way:

  @person.flights.include(:plane) 

You might want to add the :include parameter to the has_many declaration, so it will be enabled by default when loading from Person:

  has_many :flights, :include => :plane 

You can alternately add to the flight by default, as a result of which any request in flight includes its plane:

  default_scope :include => :plane 
+5
source

Just use @person.flights and set default_scope to flights to turn on the plane.
Or in your model Person: has_many :flights, :include => plane

You have to switch to Rails3, check out Active Record Queries in Rails 3 to see why!

0
source

Source: https://habr.com/ru/post/1337235/


All Articles