Rails: Pass parameter from view to controller

2019-06-25 23:58发布

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?

3条回答
Evening l夕情丶
2楼-- · 2019-06-26 00:08

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.

查看更多
够拽才男人
3楼-- · 2019-06-26 00:15

You'd want to use a nested resource

routes.rb

resources :project do
  resources :tasks
end

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:

class TasksController < ApplicationController
  def index
    @project = Project.find(params[:project_id])
    @tasks = @project.tasks
  end
end
查看更多
看我几分像从前
4楼-- · 2019-06-26 00:25

You can do like this:

 <%= link_to 'Get tasks of project', {:controller => :tasks, :action => :list_project_tasks}, :params => {:project_id => project.id} %>

Here list_project_tasks is an action in tasks_controller

 def list_project_tasks
    @project_tasks = Project.find(params[:id]).tasks
 end

Or:

You can modify you index of tasks_controller:

<%= link_to 'Get tasks of project', {:controller => :tasks, :action => :index}, :params => {:project_id => project.id} %>

def index
  @tasks = Project.find(params[:project_id]).try(:tasks) || Task.all
end
查看更多
登录 后发表回答