On May 11, 2006, at 10:46 PM, cremes.devlist@mac.com wrote:
> I''m having a difficult time wrapping my head around a set of
models
> and their associations and seeing how they map into Rails. I''ll
try
> to lay out my problem using the has_many and belongs_to structures.
> I have a RuleSpace, a Rule, and a Subject.
>
> A RuleSpace has_many Rules
> A RulesSpace has_many Subjects through Rules
>
> A Rule belongs_to (many) RuleSpaces
> A Rule has_many Subjects
>
> A Subject has_one Rule
> A Subject has_one RuleSpace
>
> So given a single Subject I should be able to find a single Rule
> and a single RuleSpace. Going the other way, given a RuleSpace I
> should find many Subjects.
>
> I''m thinking the model definitions should look like this:
>
> class RuleSpace < AR::Base
> has_many :rules
> has_many :subjects, :through => :rules
> end
>
> class Rule < AR::Base
> belongs_to :rule_space
> belongs_to :subject
> end
>
> class Subject < AR::Base
> has_one :rule
> has_many :rule_spaces, :through => :rules
> end
>
> I''m not sure at all that a call to Subject.rule_spaces will return
> only a single element. Will #has_one enforce this? Is this legal?
Answering my own question here... I continued to search the list
archives and found a similar question on March 31 2006.
Josh Susser wrote:> You can simulate has_one with a has_many with an :order and :limit
> => 1
> (though the naming is still plural, not singular).
So I guess that means I change my Subject model to look like this:
class Subject < AR::Base
has_many :rules
has_many :rule_spaces, :through => :rules, :order => ASC, :limit =>
1
end
I''m going to code this up for real and run it through some tests to
see what happens. I wonder what interesting ways it will break. :-)
cr