rails 4:活动记录关联:如何列出项目中的所有任务?

时间:2015-01-28 14:28:59

标签: ruby-on-rails ruby rails-activerecord model-associations

我创建了一个demoapp,用户可以拥有许多项目,每个项目都可以完成很多任务。

当我以用户身份登录并访问project_path时,会列出该用户的所有可用和相关项目。

但是现在,如何从该用户列出与项目相关的所有任务?

这就是我创建demoapp的方式:

rails g scaffold Project name:string user_id:integer task_id:integer
rails g scaffold Task name:string project_id:integer
rake db:migrate

[应用/模型/ user.rb]

has_many :projects
has_many :tasks, through: :project

[应用/模型/ project.rb]

belongs_to :user
has_many   :tasks

[应用/模型/ task.rb]

belongs_to :project

[分贝/ seeds.rb]

user = User.create! email: 'user@example.com', password: 'password', password_confirmation: 'password'
project = Project.create! name: 'project 1 @user', user_id: user.id
task = Task.create! name: 'task 1 @project 1 @user', project_id: project.id

user = User.create! email: 'admin@example.com', password: 'password', password_confirmation: 'password'
project = Project.create! name: 'project 1 @admin', user_id: user.id
task = Task.create! name: 'task 1 @project 1 @admin', project_id: project.id
task = Task.create! name: 'task 2 @project 1 @admin', project_id: project.id

并运行rake

rake db:reset

最后我添加了设计授权

[projects_controller.rb]

before_action :authenticate_user!
# replace all Project with current_user.projects

[tasks_controller.rb]

before_action :authenticate_user!

1 个答案:

答案 0 :(得分:0)

在你的路线文件中,输入如下内容:

  resources :projects do
    resources :tasks
  end

这会给你一条看起来像这样的路线(

project_tasks_path(project_id)

等同于:

/projects/:project_id/tasks

该路线将为您提供与该特定项目相关的所有任务。当然,您仍然需要设置控制器以从数据库中获取任务,如:

@tasks = Project.find(params[:project_id]).tasks