Newbie q on activerecord - has_one and has_many on same table?

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.

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

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
[email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs