# A new model object associated with two parents

**URL:** <https://www.ruby-forum.com/t/a-new-model-object-associated-with-two-parents/122152>\
**Category:** Rails\
**Created:** [December 5, 2007, 12:02am UTC](https://www.ruby-forum.com/t/a-new-model-object-associated-with-two-parents/122152 "2007-12-05T00:02:23Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tomn](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/c89c15/32.png) [@tomn](https://www.ruby-forum.com/u/tomn)\
**Post date:** [December 5, 2007, 12:02am UTC](https://www.ruby-forum.com/t/a-new-model-object-associated-with-two-parents/122152/1 "2007-12-05T00:02:23Z")

</div>

Please excuse me if I am asking too many questions. I’ve been  
appreciating the help (and I have been learning from reading other  
peoples questions and answers too)

Here is a cooked up example of a basic idea I am trying to accomplish

Say that I have a Pupil model . Perhaps also a Teacher, Course models.  
Teachers will have things called Course\_Offerings. To keep track of a  
pupilâ€™s performance in a course there will be a separate model called  
Course\_performances. These course\_performances will belong to both  
Pupils and to Course\_offerings. In addition to foreign keys, Iâ€™d like  
the course\_performance records to have their own copy of the Pupils  
“full\_name” for easy access in views.

Given a list of Pupils, is the code below an efficient way of creating a  
course\_performance instance and associating it with (and assuring that  
it gets foreign keys from) two separate models it belongs to?

Do I need to save the new course\_performances at all or will they get  
saved as I associate them to parent classes?

Will the “transaction” work the way I have it or should I chose the name  
of the whole database to apply the transaction to? (I wasn’t clear on  
what the book meant me to use)

def create\_course\_performances  
@pupils\_to\_add = Pupil.find(:all, :conditions =\> [â€œsome\_condition =  
“something” ] )  
@course\_offering =  
Course\_offering.find\_by\_id(params[:course\_offering\_id]

```
 @pupils_to_add.each do |current_pupil|
    holder = Course_performance.new(:name => current_pupil.full_name

```

)

```
      Pupil.transaction do
        current_pupil.course_performances << holder
        @course_offering.course_performances << holder
      end
 end

```

end

Thanks in advance for any tips.
