0

This might be a silly question but I'm slightly confuse here :

I have a user model, which has 2 attributes : hair and eyes, that can have a color value.

Instead of referencing the color as a string twice in the hair and eye column of the user table, I'd rather have a separate Color model associated to my User model that my attributes will point at.

I can't figure out how to do that. Do I need has_one, has_many, or polymorphic associations ? How do I set up my User and Colors models ? Do I need to create specific models for hair and eye ?

Here is what I want in a rails console :

u = User.first  
u.update_attribute(:hair, Color.find_by_name("blue")  
u.update_attribute(:eyes, Color.find_by_name("green")  
u.save  

u.eyes # green  
u.hair # blue  

I know this is a pretty basic question, but I really need some help here !

Thanks ;)

cl3m
  • 2,791
  • 19
  • 21

1 Answers1

1

User scheme should contain hair_color_id and eyes_color_id fields

class User < ActiveRecord::Base
  belongs_to :hair_color, class_name: "Color"
  belongs_to :eyes_color, class_name: "Color"
end

So.

u = User.new
u.hair_color = Color.find_or_create_by_name("blue")
u.eyes_color = Color.find_or_create_by_name("green")
u.save
...
u.hair_color.name
#=> blue
fl00r
  • 82,987
  • 33
  • 217
  • 237