Rails: Pass parameter from view to controller

混江龙づ霸主 提交于 2020-01-14 10:34:29

问题


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:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/15665546/rails-pass-parameter-from-view-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!