Rails:将参数从视图传递到控制器 [英] Rails: Pass parameter from view to controller
问题描述
我在rails中有以下模型:
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
我有一个视图,列出了可用的项目点击任何项目,我想打开一个页面,其中列出了所点击的项目中的所有任务。现在的问题是如何传递项目ID?我还希望项目的id在许多控制器之后可见,所以我想我应该使用会话变量或类似的东西。
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?
推荐答案
您想要使用嵌套资源
routes.rb
routes.rb
resources :project do
resources :tasks
end
允许您执行<%= link_to'Tasks',tasks_project_path(@project)%>
您将有一个任务的控制器,参数将包括:project_id / projects /:project_id / tasks
Then you'd have a controller for tasks, the params would include the :project_id /projects/:project_id/tasks
然后在控制器中:
class TasksController < ApplicationController
def index
@project = Project.find(params[:project_id])
@tasks = @project.tasks
end
end
这篇关于Rails:将参数从视图传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!