Reputation: 1050
First, I apologize if this is too much of a newbie question. I can only code on my spare time so I'm often re-learning things from scratch on every project.
I have a Class, Person
, with the attributes name
, birth-date
, and gender
, so I can create, say, Michael, a 24 year-old male, and Belinda, a 17 year-old female.
However, there are other hidden, predefined attributes that should be assigned automatically to those people based on age and gender. They are not defined by a human on creation, and cannot be edited by the user later.
So, for example, we can have the hidden attributes favorite-book
and favorite-movie
, and they will be different depending on whether the Person
is a male under 18, a male 18-40, or a male over 40; or a female under 18, a female 18-40, or a female over 40.
How should I go about this? Should I create those attributes in the Person
profile, but not show them on the interface and just fill them out automatically depending on the input? Or create those other attributes as something like "categories," and assign the people to one of them? Keep in mind I'll have to use this information often, in the interface, and the people should change groups automatically as they age.
Also, how does doing this look like in Rails? Someone told me to "use hashes," but I'm unclear on the nuts and bolts of this approach.
Upvotes: 0
Views: 110
Reputation: 3376
I think your first suggestion should work just fine "create those attributes in the Person profile, but not show them on the interface and just fill them out automatically depending on the input". Unless this extra data you are trying to say if elaborate or huge, storing it in the Person model should be fine. An implementation of something like this will look like:
class Person < ActiveRecord::Base
after_validation :assign_favorites, :on => :create
def assign_favorites
if self.age < 18 && self.sex == 'male'
self.favorite_book = 'Hunger Games'
elsif self.age >= 18 && self.sex == 'male'
...
end
end
end
Upvotes: 1