brain.rbinstance_missing
The best way to get started with Rails 2.x nested routing and routing at all, is to read the official Rails Routing guide at the Rails Guides website.
/tasks/?project_id=1
/projects/1/tasks
- /app/models/project.rb
class Project < ActiveRecord::Base
has_many :tasks
end
- /app/models/task.rb
class Task < ActiveRecord::Base
belongs_to :project
end
# /config/routes.rb map.resources :projects, :has_many => :tasks # and the correspondent task resource map.resources :tasks
Adding the second routes, that defines a RESTful route to :tasks, depends if you would like to allow an access to the Task resource, without the project context, this is not a must.
map.resources :projects do |project|
project.resources :tasks
end
map.resources :projects do |project|
project.resource :design_document
end
$ rake routes
$ rake routes | grep project
map.resources :projects will produce:
events GET /projects
formatted_projects GET /projects.:format
POST /projects
POST /projects.:format
new_project GET /projects/new
but for a Nested route, like we defined before will produce:
project_tasks GET /projects/:project_id/tasks
new_project_task GET /projects/:project_id/tasks/new
edit_project_task GET /projects/:project_id/tasks/:id/edit
project_task GET /projects/:project_id/tasks/:id
/projects – list all projects
/projects/1 – show a single project
/projects/1/design_document – a project�s design document
new_project_task(@project)
- or when both resources are required
edit_project_task(project, @task) </pre> <br /> <h2>Forms</h2><br /> I'll assume you use form_for in your forms, it will make the usage of nested resources a lot easier than to work with plain HTML or form_tag.<br /> The regular form we know of form_for, receives one instance as the form object:<br /> <pre class="brush: rails"> <% form_for(project) do |f| >
…
< end >
< form_for([ @project, @task ]) do |f| >
…
< end %>
/projects/1/tasks/new
before_filter to get the project instance:private
def get_project
@project = Project.find(params[:project_id])
end
So we’ll have our parent resource whenever we do it. in our actions we can use the parent resource instance to create the nested resource:
- TasksController
def create
@project.tasks.build(params[:task])
if @project.save
respond_to …
end
else
respond_to …
end
end
end
Using nested resources and routes is the right thing, URLs are clear, and code is readable. but:
| Variable | Value |
|---|---|
| GITHUB | |
| WWR | { :working_with_rails => 'http://www.workingwithrails.com/person/5844-elad-meidar' } |
| IRC | { 'irc.freenode.net' => [ '#rubyonrails', '#railsbridge', '#ruby', '#mootools' ]} |
| SKYPE | eladmeidar |
You're seeing this error because I think it is funny.