# Newbie q on activerecord - has\_one and has\_many on same table?

**URL:** <https://www.ruby-forum.com/t/newbie-q-on-activerecord-has-one-and-has-many-on-same-table/195986>\
**Category:** Rails\
**Created:** [October 4, 2010, 8:31pm UTC](https://www.ruby-forum.com/t/newbie-q-on-activerecord-has-one-and-has-many-on-same-table/195986 "2010-10-04T20:31:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![JoshK](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4da419/32.png) [@JoshK](https://www.ruby-forum.com/u/JoshK)\
**Post date:** [October 4, 2010, 8:31pm UTC](https://www.ruby-forum.com/t/newbie-q-on-activerecord-has-one-and-has-many-on-same-table/195986/1 "2010-10-04T20:31:24Z")

</div>

Hi I have a table where I need to identify one of the children as the  
“prime” child.

So, its like:

Parent  
has\_many :Child  
has\_one: Child :as :prime\_child (?)

or something like that? Do I put something like prime\_child\_id in the  
Parent table?  
Thanks.

---

<div class="post-metadata">

**Author:** ![JoshK](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4da419/32.png) [@JoshK](https://www.ruby-forum.com/u/JoshK)\
**Post date:** [October 4, 2010, 10:15pm UTC](https://www.ruby-forum.com/t/newbie-q-on-activerecord-has-one-and-has-many-on-same-table/195986/2 "2010-10-04T22:15:34Z")

</div>

Parent  
has\_many :children  
scope :primary, where(:role =\> ‘primary’)

Or something like that. The syntax of scope, or named\_scope differs  
depending on the version of Rails, but you get the idea… You’ll  
probably want to add code to make sure that only one child has the  
primary role for a particular parent.

HTH

---

<div class="post-metadata">

**Author:** ![JoshK](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4da419/32.png) [@JoshK](https://www.ruby-forum.com/u/JoshK)\
**Post date:** [October 4, 2010, 10:27pm UTC](https://www.ruby-forum.com/t/newbie-q-on-activerecord-has-one-and-has-many-on-same-table/195986/3 "2010-10-04T22:27:13Z")

</div>

JoshK wrote:

> Hi I have a table where I need to identify one of the children as the  
> “prime” child.
> 
> So, its like:
> 
> Parent  
> has\_many :Child  
> has\_one: Child :as :prime\_child (?)
> 
> or something like that? Do I put something like prime\_child\_id in the  
> Parent table?  
> Thanks.

Yes. You should be able to do  
class Parent \< AR::B  
has\_many :children # not :Child !  
has\_one :prime\_child, :class\_name =\> ‘Child’  
end

The two associations are completely independent. The fact that they  
refer to the same child class and table is irrelevant.

## Best,

Marnen Laibow-Koser  
[http://www.marnen.org](http://www.marnen.org)  
removed\_email\_address@domain.invalid
