I have the following models in rails :
class Task < ActiveRecord::Base
attr_accessible :description, :name, :project
belongs_to :project
validates :name, :presence => true
end
class Project < ActiveRecord::Base
attr_accessible :name
has_many :tasks
end
I have a view that lists the projects available On click on any of the project I want to open up a page that lists all the tasks in the clicked project. Now the question is how do I pass the project id? I also want the project id to be visible in many controllers after that so I think I should use session variables or something like that?
1) On click on any of the project I want to open up a page that lists all the tasks in the clicked project. - To do this, I suggest using the link_to helper that Rails provides, and linking to the item via the Rails routing. For example, your view would list all the projects, and each project item would be displayed using
<%= link_to project.name, @project %>
or<%= link_to project.name, project_path(@project) %>
You can see a list of routes by typing rake routes in the command line.
2) I'm not sure exactly what you mean, but if the url you are using is something like /projects/12/ any resources and their controller below (such as /projects/12/tasks/15) can access the project_id as params[:project_id], assuming your routes are set up as nested routes.
You'd want to use a nested resource
routes.rb
Which would allow you to do
<%= link_to 'Tasks', tasks_project_path(@project) %>
Then you'd have a controller for tasks, the params would include the :project_id
/projects/:project_id/tasks
Then in the controller:
You can do like this:
Here
list_project_tasks
is an action intasks_controller
Or:
You can modify you
index
oftasks_controller
: