I'd create a table (as persons) related to another (as animals), to
selecting the animals prefered for each person but indicating too
wich is the most prefered. My idea would be use 'has_many' to relating
some animals and 'has_one' for the most prefered (that would not be in
the another relation).
Do you know another solution better that this? Thanks in advance!
2) just have a flag prefered in animals
then in persons
class Person < ActiveRecord::Base
has_many :animals do
def prefered
find(:first, :conditions => {:prefered => true})
end
end
But with this option, does each person could have a different prefered
animal?
the way you described your setup:
animal belongs_to person
would mean, that a animal record can belong to only one person
so i assumed, that you talk about 'named' animals
so a person has a cat named "foo"
another person a cat named "bar"
if you want to have a set of animals (horse, cat, dog)
of which each person can chose some and set one as prefered
you would need a habtm relationship
each person can have many animals
each animal can belong to many persons
in your case, where you need additional information (prefered)
you should create an intermediate model
But with this option, does each person could have a different prefered
animal?
Not easily. There is no way (AFAIK) to put a relationship between two
relations in Rails that enables the related has_many model to remain
independent of the primary model. I'm happy to be proven wrong...
One solution is to override methods in your Person model for setting the
animals and preferred animal. These methods can do the validation, so
setting the preferred animal checks it is contained in the animals list
and removing an animal from the animals list can check if it is the
preferred animal (and either fail or remove the preferred animal
depending on how you want it to function).
Not easily. There is no way (AFAIK) to put a relationship between two
relations in Rails that enables the related has_many model to remain
independent of the primary model. I'm happy to be proven wrong...
OK, yes, I missed the fact this is really (by the sound of it) a
has_and_belongs_to_many relationship and so Thorsten is obviously right.
An intermediate relationship is the way to go. Preference is then
defined there.