I have an Rails 3.2 app, and I have one model, let’s call it Car.
The user inputs a series of information, and the app returns a list of suggested cars based on that information. Now, each car has a set of transient properties that a user may or may not want, such as suggested upholstery, suggested color, etc. These “suggested” properties are calculated on the fly based on the information the user enters. So not only does the app guess what cars the user might want, it also guesses what additional options the user might want, and stores that information transiently on the Car record.
This is a pseudocodish representation of the relevant part of the Car model:
def self.suggested_cars
@cars = basic_cars(user_height, user_weight)
add_upholstery_suggestions(@cars, user_wealth)
add_color_suggestions(@cars, user_gender)
end
The issue is that the algorithms for suggesting cars and options can return actual Car records that are not distinct. For example, one request for suggested cars can return Both Car A and Car A with leather seats. But then I have an issue, because when requesting two of the same entity from active record at the same time, both instances refer to the same object, i.e. they can’t have different transient data.
I suspect that I might need to use the .dup method to copy objects when that happens, but I feel like there is a more elegant solution. I’m open to any suggestions. Is there a common way to handle this type of situation?
The problem is that you have two different things that you’re trying to force into one. One is a list of car types; the other is a list of car configurations. A car configuration has one car type. A car type has many configurations.
Fix by turning them into two different classes, e.g.: