# Active Record associations question

**URL:** <https://www.ruby-forum.com/t/active-record-associations-question/131188>\
**Category:** Rails\
**Created:** [March 6, 2008, 7:59pm UTC](https://www.ruby-forum.com/t/active-record-associations-question/131188 "2008-03-06T19:59:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [March 6, 2008, 7:59pm UTC](https://www.ruby-forum.com/t/active-record-associations-question/131188/1 "2008-03-06T19:59:16Z")

</div>

Hi

Something I’m doing works magically in Rails and I’m trying to figure  
out how 🙂

Lets say I have a Post model which has many Comments

Within my Comment model I have this:

def foo(title)  
self.create(:title =\> “title”)  
end

Then I do this:  
Post.find(4).foo(“hello”)

Rails creates a new Comment with a post\_id of 6… How does it know to  
do this!? Where does it get the correct post\_id from?

This has really been puzzling me.

Thanks a lot  
Ryan

---

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [March 7, 2008, 10:53am UTC](https://www.ruby-forum.com/t/active-record-associations-question/131188/2 "2008-03-07T10:53:01Z")

</div>

On 6 Mar 2008, at 18:58, Ryan wrote:

> def foo(title)  
> self.create(:title =\> “title”)  
> end
> 
> Then I do this:  
> Post.find(4).foo(“hello”)
> 
> Rails creates a new Comment with a post\_id of 6… How does it know to  
> do this!? Where does it get the correct post\_id from?

I assume that you meant to type Post.find(6).comments.foo(‘hello’)  
In general any class method on a model will be available as a scoped  
method on an association collection. The comments object is special:  
it’s an association collection (not just a dumb) array, so it knows  
that it belongs to that particular instance of post. If it doesn’t  
know how to handle a method, it will just pass it on to the class  
(here Comment) having previously scoped it (via with\_scope)

Fred

---

<div class="post-metadata">

**Author:** ![ryan](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a8b319/32.png) [@ryan](https://www.ruby-forum.com/u/ryan)\
**Post date:** [March 7, 2008, 11:04pm UTC](https://www.ruby-forum.com/t/active-record-associations-question/131188/3 "2008-03-07T23:04:04Z")

</div>

Yeah, thats what I meant to type 🙂

Thanks for the help

On Mar 7, 11:45 am, Frederick C. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
