
I have this table which contains a field called ‘icon_for’ which I have been using to check if the icon can be used for a ‘User’ or a ‘Greeting’.
This is obviously not the best way to do this as if I want to use an icon for say both a ‘Greeting’ and a ‘User’ or even some other object I would be stuck.
Do I need to make another table called icons_object and then list the icon_id and object_name?
Seems like I would have to do a lot of repeating of the icon_id’s if an icon is used for several objects but is this the way to go?
Also what would this table association in Rails be. Say the Table is called icons_objects.
Then in Rails would it be
Icon.rb
icon has_many :icon_objects ?????
Totally confused here so any help for a NOOB would be appreciated.
Is there a way to do this normalized?
You want to use polymorphic associations. For example:
Then you could get to icons from greetings or user:
Or if you wanted to query icons for a particular type:
This approach is not unlike the one you have already taken. The benefits of doing this method is that you can get the parent object without worrying about what type it is, like you would if you tried to implement the other answer in this thread.
You will just need to run some migrations to get everything working properly. You can see more information at http://guides.rubyonrails.org/association_basics.html#polymorphic-associations.
Edit per comment:
Strictly speaking, you’re correct. You cannot have a polymorphic record which points to a User and a Greeting. However, you can make a small change and create another model, which would kind of act like a join table.
Each IconConnection would point to either a Greeting or a User, and each of the IconConnections would point to the same Icon.
This setup assumes that you can have multiple icons for each user and greeting, but if not, you can replace the
has_many‘s withhas_one‘s