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?
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)