A collection of other Rails 4 models

I’m not sure how to say this, because I’m not sure what the correct term is, but ..

I have a user model. This model can create Trains. so user.trains has all its trains. This model can also create Buses, so user.buses has all its buses. Trains and buses may contain cargo. user.trains.cargo and user.buses.cargo.

How can I configure this so that I can just ask User.cargo and get all the freight from both trains and buses without having to call up a .cargo list for everyone?

+2
source share
3 answers

The answer to the inheritance of one table may be excellent for you, especially if Trains and Buses have basically the same data about them. However, if these models are very different from each other, you may need a different solution.

What if you define a simple method for your custom class?

class User has_many :trains has_many :buses def cargo trains.map(&:cargo) + buses.map(&:cargo) end end 

This answer assumes that each Bus and Train has a load that is different from your example showing User.trains.cargo .

+2
source

You can use the concept of unidirectional inheritance in rails.

Since you have both Trains and Buses , both of which can be called Vehicle types, you can have the basic Vehicle model, and let both Train and Bus inherit from Vehicle as follows:

 class Vehicle < ActiveRecord::Base; end class Train < Vehicle; end class Bus < Vehicle; end 

And then your User class can have a one-to-many association with Cargo through Vehicle .

Similarly, if you call user.cargoes ( User as an instance of User ), the result should be all the loads of the specified user.

Hope this sheds light on this issue for you ...

+2
source

I have not tried this, but active_record_union seems promising.

 class User < ActiveRecord::Base has_many :buses has_many :trains scope :cargoes, ->{buses.select(:cargo).union_all(trains.select(:cargo))} end 
+2
source

All Articles