Forum: Ruby on Rails can I fake has_one :through?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A0c079a7c3c9b2cf0bffebd84dc578b0?d=identicon&s=25 unknown (Guest)
on 2006-05-12 05:46
(Received via mailing list)
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?

cr
A0c079a7c3c9b2cf0bffebd84dc578b0?d=identicon&s=25 unknown (Guest)
on 2006-05-12 15:26
(Received via mailing list)
On May 11, 2006, at 10:46 PM, cremes.devlist@mac.com wrote:

>
>   has_many :rules
>   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
This topic is locked and can not be replied to.