The answer may be different regarding what you want to achieve. Do you want to retrieve those attributes or to use them for querying ?
Loading results
ActiveRecord is about mapping table rows to objects, so you can’t have attributes from one object into an other.
Let use a more concrete example : There are House, Person and Dog. A person belongs_to house. A dog belongs_to a person. A house has many people. A house has many dogs through people.
Now, if you have to retrieve a dog, you don’t expect to have person attributes in it. It wouldn’t make sense to have a car_id attribute in dog attributes.
That being said, it’s not a problem : what you really want, I think, is to avoid making a lot of db queries, here. Rails has your back on that :
# this will generate a sql query, retrieving options and model_options rows
options = model.options.includes( :model_options )
# no new sql query here, all data is already loaded
option = options.first
# still no new query, everything is already loaded by `#includes`
additional_data = option.model_options.first
Edit : It will behaves like this in console. In actually app code, the sql query will be fired on second command, because first one didn’t use the result (the sql query is triggered only when we need its results). But this does not change anything here : it’s only fired a single time.
#includes
does just that : loading all attributes from a foreign table in the result set. Then, everything is mapped to have a meaningful object oriented representation.
Using attributes in query
If you want to make query based on both Options and ModelOptions, you’ll have to use #references
. Let say your ModelOption has an active
attribute :
# This will return all Option related to model
# for which ModelOption is active
model.options.references( :model_options ).where( model_options: { active: true })
Conclusion
#includes
will load all foreign rows in result set so that you can use them later without further querying the database. #references
will also allow you to use the table in queries.
In no case will you have an object containing data from an other model, but that’s a good thing.