In Ryan Bates’s first episode on complex forms, he adds the following to a model:
# models/project.rb
has_many :tasks
def task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
I’ve never thought about this before, but how does the Project model know what “tasks” of which Project instance? Does that come from the has_many association? Is it like, when the project is running and I’m viewing a Project, that’s the “active” object so project.rb knows which Project object we’re referring to, so it knows that tasks is really some_current_project.tasks? (I’m obviously grasping at straws here.)
Also, if someone would point me to some reference that explains other questions like this one, I’d really appreciate it.
I hope my question is clear. Please ask for more clarification in comments if needed.
Please note: I know that Active Record handles CRUD actions and that objects correspond to rows in tables, etc. Those are just descriptions of what Active Record is. I’m looking for how it works when the project is running. I also now the constructs MVC, but I can’t seem to find a detailed explanation of what information is sent where with respect to Rails.
(Not sure I fully understood your question, feel free to let me know if that’s the case.)
A rails model is basically a ruby class that is persisted to a database. So it acts like a normal ruby object for the most part, with some database magic mixed in.
You tell rails which project instance to load (e.g. by providing an
id), and it loads the data from the database.Then, when you call
project.tasksis when the magic happens: theProjectmodel has notasksmethod, so it will trigger ruby’smethod_missingmethod. This will then load the associated records into model instances and provide access to them via a rails object.Since a
projecthas manytasks, rails knows it should look into thetasksdatabase and load the rows whereproject_idis equal to theprojectmodel’sidattribute.In short, ruby meta-programming and monkey patching possibilities make much of rails’ magic possible.
(Edit for question on routing.)
When you want to edit project number 13, you go to a URL that looks something like http://www.mysite.com/projects/13/edit. If you look at
routes.rbin yourconfigdirectory, you’ll see (in Rails3)resources :projectswhat Rails does is set up all sorts of paths for you. Behind the magic, the edit path looks likeThis basically says “when a user wants to see http://www.mysite.com/projects/13/edit, send him to the
editaction in theprojectscontroller and set theidparameter to the value that’s in that place.Then in your controller, you’ll load the appropriate project with
In a similar way, you could do this (this is an dumb example):
In
routes.rb, putAnd then in you controller
So rails basically uses magic to assign values in the URL to params you can work with in your controller. You can read more about routing here: http://guides.rubyonrails.org/routing.html